I am making a react login app connected to an express server and everything works fine and now I am trying to handle errors. When the user sends username and password I check on express if the user exists in the db, and if it doesn't then I set the status at 404 and send json error that I want to grab in the front end to display that error in an alert. The problem is that even though in the frontend I am getting the 404 error, the json array of message doesn't appear. This is my code:
router.post('/login', async (req, res) => {
const { username, password } = req.body;
// check if user exists
const user = await User.findOne({ username });
console.log('user: ', user);
// if the user doesn't exst
if (!user) {
return res.status(404).json({
erros: [
{
msg: 'No user found',
},
],
});
}
And this is the error I am getting:
Any idea why the array of error is not sent to the front?
CodePudding user response:
assume you are using axios in frontend, that will fall to .catch
, so it will be like this
axios.post(...).catch((error) => {
console.log(error.response.data) // <- that's your response data
});
your code works, just wrong way to catch at frontend
CodePudding user response:
Please use the below code to send json object along with status code 404
res.status(404).send({
erros: [
{
msg: 'No user found',
},
],
});