Reputation: 605
I'm working on a post route for an express.js server. I've got a validation function that if not passed, returns a 400 code with message. The client (React), receives the 400 code, but I cannot access the message sent by the server.
This is within the POST in express:
const { error } = validate(req.body);
if (error)
return res
.status(400)
.send(error.details[0].message);
This is the submit routine in React:
doSubmit = async () => {
const { username, password } = this.state.data;
const result = await login({ mail: username, password });
console.log('result', result);
};
Login is only a wrapper for axios.post method:
export async function login(user) {
try {
return await http.post(apiEndpoint, user);
} catch (ex) {
console.log(ex.message);
return ex;
}
}
Currently, the code works as it is. Submitting an invalid input, such as a password below 5 characters, i get the following in the client:
POST http://localhost:3000/api/auth 400 (Bad Request)
Request failed with status code 400
result Error: Request failed with status code 400
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:78)
at XMLHttpRequest.wrapped (raven.js:363)
However, if I change the status code sent by the server to "200", I get:
result { full response here along with data property.. data: ""password" length must be at least 5 characters long" }
I've been reading the Express documentation. It doesn't say anything about not sending the response if the code is 400 (although it makes sense to send nothing if bad request). I've also toyed a bit with 'body-parser' but didn't get different results.
However, if I test in postman, it works like a charm! With same input, i get the status code and the message.
Finally, it's ok to validate both the input sent (client) and the data received(server) right? If so, let's say the client is OK with the input, but the server is not. Should the server respond with whatever the problem is (what i'm trying to achieve), or simply say 'ERROR' (current scenario)?
Thank you.
Upvotes: 2
Views: 947
Reputation: 605
Well, in the end, the problem was accessing ex.message, instead of ex.response ... Cheers.
Upvotes: 1
Reputation: 899
Axios code example, may be given code fix your issue. The issue is with your parameters.
axios({
url: '/login',
method: 'post',
params: { username: 'cedas', password: 'fredsed' }
}).then(response => {
resolve(response)
})
.catch(error => {
reject(error)
});
})
Upvotes: 1