Axios auth request web site - javascript

I am trying to enter a website by submitting login data with axios. But each time the response.data is the site's login html page. When I want to access the site and get the data from my profile. How can I solve? how do i get the cookie token?
This is my code. Where i wrong?
await axios.post('https://namesiteweb.com/login.html',
{
'username': 'username',
'password': 'password'
}
).then(response => {
console.log(response);
}).catch(err => {
console.log(err);
});

Related

Axios POST request returns 404 error when sending to Node.js API

I am developing a web application using a React frontend and a Node.js backend. The frontend sends a POST request to the backend using Axios like this:
Register.js
...
handleSubmit = (e) => {
e.preventDefault();
const { email, password, name, dateofbirth } = this.state;
const user = { email, password, name, dateofbirth };
const url = "http://localhost:9000/register";
axios
.post(url, user, {
headers: {
"Content-Type": "application/json",
},
})
.then((response) => console.log(response))
.catch((error) => {
console.error("You have made a big error. " + error);
console.log(user);
});
};
...
While the backend receives the request like this:
./routes/register.js
...
router.post("/register", async (req, res) => {
console.log("Inside Home Login");
res.writeHead(200, {
"Content-Type": "application/json",
});
console.log("Users : ", JSON.stringify(users));
res.end(JSON.stringify(users));
})
...
However I get the error "POST http://localhost:9000/register 404 (Not Found)" upon trying to send anything.
My guess would be that you are routing in your index.js. If you can provide a code sample to figure it out.
If so, the thing is defining a routing like,
app.use('/register', yourImportedVariable);
does define a route at http://localhost:9000/register.
So, if in your routes/register.js file you define a GET endpoint with '/register' your front-end call must be http://localhost:9000/register/register
To fix it, either rename your route as '/', or fix your front-end call with the above url.

Server status 400 blocks json from sending response to client

I'm currently developing client side for my app.
When i try to login user in case where email and password is correct everything works fine but sending error data isn't occuring because status(400) blocks it.
Here is part of my server side code for user login that isn't sending object with isAuth, message, err:
User.findOne({ email: req.body.email }, (err, user) => {
if (!user) return res.status(400).json({
isAuth: false,
message: "Auth failed, bad email",
err
})
But when I make it like that i get the error with all parameters:
User.findOne({ email: req.body.email }, (err, user) => {
if (!user) return res.json({
isAuth: false,
message: "Auth failed, bad email",
err
})
Another strange thing is that when I send bad request with Postman I'm getting all the response data.
And here is client side function that is making request, the console.log(request) part is blocked because of status 400:
const submitForm = async (e) => {
e.preventDefault()
const request = await axios.post('/api/login', { email: email, password: password }).then(res => res.data)
console.log(request)
dispatch({
type: "USER_LOGIN",
payload: request
})
}
And here is some of Chrome stuff from console:
xhr.js:166 POST http://localhost:3000/api/login 400 (Bad Request)
createError.js:17 Uncaught (in promise) Error: Request failed with status code 400
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
There was an axios error/bug.
I have rewrited my code using fetch API. It seems that axios has some kind of bug when it comes to handling 4xx and 5xx status.
Now client part looks like this:
const submitForm = async (e) => {
e.preventDefault()
const request = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password }),
headers: {
'Content-Type': 'application/json',
}
}).then(res => res.json())
console.log(request)
dispatch({
type: "USER_LOGIN",
payload: request
})
}
At the server side everything is just as it should be, return res.status(400).send(data)

Can't set user session with Vue and Django

I have the Vue app and the Django rest framework api separately.
One on localhost:8080 (vue app) and the rest api on localhost:8000.
So, I created an APIView that is supposed to log the user in when they make a post request:
class LoginUserAPIView(APIView):
permission_classes = () # login should be accessed by anyone, no restrictions.
def post(self, request, format=None):
username = request.data['username']
password = request.data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
user = UserSerializer(user)
return Response({'success': 'Logged in', 'user': user.data})
return Response({'wrong': 'username or password not correct, try again'}, status=status.HTTP_401_UNAUTHORIZED)
And I was trying to get the user session from django with axios:
login() {
this.isLoading = true;
return axios({
method: 'post',
url: 'http://localhost:8000/api/login_user',
data: {
username: this.name,
password: this.password
},
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
this.$store.commit('loginAuth', true); // setting isAuth to true in vuex store.
this.$store.commit('setUser', response.data.user); // to access the user object since I don't use django templates
this.$router.push({name: 'page'}); // redirect to random test page that requires authorization so I can see if everything went fine.
})
.catch(err => {
console.error(err);
if (err.response.status == 401) {
alert(err.response.data.wrong);
this.isLoading = false;
}
})
but I was naive and I thought this would work, so when I checked the vue app for any cookies or sessions, nothing.
How could I set user session for a separate vue app?
Thanks in advance, I apologize for my lack of knowledge.

Fetch post without refreshing - Vanilla JavaScript and Express.js

I'm making a Express.js app which has a form to send contact info to a mail address with a post function. I'm using a "front-end post" because if I do it entirely from the backend I need a route to go after the post.
I want to post the info without refreshing the page, but I can't make it.
My front-end code:
formButton.addEventListener("click", ()=>{
fetch('http://localhost:3000/contact', {
method: 'POST',
body: JSON.stringify({
nombre: form.elements["nombre"].value,
email: form.elements["email"].value,
consulta: form.elements["consulta"].value
}),
headers:{
'Content-Type': 'application/json'
}
}).then(response=>{
if(response.ok){
return response.json;
}
throw new Error('Request failed');
}, newtworkError => console.log(networkError.message)
).then(jsonResponse =>{
console.log(jsonResponse);
});
});
And the server side code to handle the request is:
app.post('/contact', (req,res)=>{
sendMail(req.body.nombre, req.body.email, req.body.consulta);
});
The mail is sent with the sendMail function using nodemailer, and it works, but after execute the function the page refreshes and in the url bar appears the url "http://localhost:3000/?nombre=XXX&email=XXX%40XX&consulta=XX".
How can I do the post without refreshing?

How to handle expired jwt token in react redux?

I'm developing the application with react js and redux. For backend i used java to create api's. So far i have created three services, login, signup, listing. I have used jwt token for listing service to secure the incformation. I have set jwt token expiration time is 10 mins in backend. Each 10 mins the jwt token will get expired and for new token i need to login again. This is what i have done in backend.
I have integrated those services in my react with redux concept. The problem which i'm getting is, each i need to go login screen for new token. I want this to be happen in background. How to do with redux?
export function handleResponse(response) {
if (response.ok) {
return response.json();
}
// If invalid jwt token the page will get redirect to login.
if (response.status === 401) {
localStorage.clear();
alert('Session expired!');
location.href = '/login';
}
}
export function loginAction(data) {
const resObject = {
username: data.username,
password: data.password,
};
return dispatch =>
fetch(`/login`, {
method: 'post',
body: JSON.stringify(resObject),
headers: {
'Content-Type': 'application/json',
Authorization: `Basic ${basicAuth.authSecret}`,
},
})
.then(handleResponse)
.then(res => dispatch(loginUser(res)));
}

Categories

Resources