Reputation: 696
I am trying to authorize a user. I have made a login form. And after filling the form and clicking the login button the user should be authorized.
This is what I tried:
axios.post('http://localhost:4000/users', {}, {
auth: {
username: nameInForm,
password: passwordInForm
}}).then(function(response) {
alert("Authenticated");
}).catch(function(error) {
alert("Error on Authentication");
});
Source: https://github.com/mzabriskie/axios
This is json data in my fake server:
"users": [
{
"id": 1,
"username": "admin",
"password": "admin"
}
]
But even if I enter wrong username and password in the login form and I click the login button I always get the 'Authenticated' alert and a new user is created in the json fake server. I want to show the 'Error on Authentication' alert when I enter wrong username and password and show the 'Authenticated' alert when I enter the correct username and password.
Upvotes: 0
Views: 258
Reputation: 949
You need to handle response. For example, your response is for a successful login should be like that:
"users": [{
"id": 1,
"username": "admin",
"password": "admin" // You shouldnt include password on the response for security concerns
}]
If your credentials are wrong your server should return like that:
"users": []
(also, including a success attribute will be great.)
Then you need to handle/differentiate this 2 different responses on Reactjs side. For example your code should be like that:
axios.post('http://localhost:4000/users', {}, {
auth: {
username: nameInForm,
password: passwordInForm
}}).then(function(response) {
if (response.data.users) {
alert('Authenticated');
} else {
alert('Wrong Credentials');
}
}).catch(function(error) {
alert("Error on Authentication");
});
Upvotes: 1