everything was working fine. Now, for some reasons, when I get an error (for example invalid password) the error that I throw instead of being json is html.
So here is how I normally define an error:
try {
const errors = validationResult(req)
// some code
if(!isEqual) {
const error = new Error('invalid password, please try again');
error.data = errors.array();
error.statusCode = 401;
throw error; // I throw the error going to the catch block
} catch (err) {
next(err) // from the catch block I go to the error middleware
}
error middlware looks like this one:
app.use((error, req, res, next) => {
console.log('error middleware: ' + error);
const message = error.message;
const status = error.statusCode || 500;
const data = error.data;
res.status(status).json({ message, data }); // I also tried returning this with no success
});
and, on my frontend (react) I have the following:
await fetch(`http://localhost:8090/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
credentials: "include",
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
}),
})
Anybody knows why the errors instead of being in json format they are sent in html?
I am experiencing this with every single error that might occur to a user.
So the error that I keep receiving is this one: SyntaxError: Unexpected token < in JSON at position 0 because, of course, the errors are sent as html.
I normally use these errors in the frontend in order to show the user if something went wrong (for example the invalid password).
req headers are fine and response header is text/html. Plus, if I click on "response" instead of seeing the data as json I see them as html codes (so with all the tags html, body and the error is in a pre tag that, to be honest, I don't know what it is
Thank you in advance. If, for some reasons I am going against stackoverflow policies, please tell me and I will update my question.