2

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.

4
  • Have you looked into the devtools -> Network tab to see what data it actualy returns? Ideally make a screenshot and add it to your question. I'm pretty sure the data is not errors in html. Commented Feb 25, 2021 at 16:07
  • Hi, req headers are fine and response header is text/html, sorry if it wasn't clear. 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 Commented Feb 25, 2021 at 16:14
  • Well i guess that it is not your error middleware responding then. Try to comment it out and if you still see the same html response then there's a problem somewhere else. Commented Feb 25, 2021 at 16:18
  • Hi, you are actually right and none of these codes is causing the issue. Once I figure out what is causing the issue I will update my question and put an answer in order to help other devs in the future. Thank you for your answer though, I really appreciate it! Commented Feb 26, 2021 at 8:51

2 Answers 2

3

the issue you are facing is related to express not recognizing your error handler properly for fixing it you should ensure multiple things

  1. Error handler registration after all other routes and middleware
  2. All the 4 arguments should be present even if you don't use them (error,req,res,next)
Sign up to request clarification or add additional context in comments.

Comments

1

If you are using express, check if you have app.use(express.json()); before the error middleware.

Plus there are some ways to return json properly, try some of them too: Proper way to return JSON using node or Express

4 Comments

I'm not sure what you have in the variable server but I got the body parser in order to read json. As molda suggested in the comment, I did comment out the error middleware and I still have the same issue. Once I figure out what is causing the issue I will update my question with the codes that I did not put here (because I don't know which one they are) and put an answer in order to help others in the future. By the way, thank you for the time that you spent by replying to me, I really appreciate it.
oh I forgot that the world is using app for express instance name, except me :) edited.. my next try would be something different than errors.array() in your error.data
I found a solution that is pretty much the same code so, to be honest, I have no idea one works and the other not (that was working fine till now). Oh, thank you! if it wasn't for you I wouldn't have thought of this solution!
happy to hear that you solved your problem, feel free to accept an answer so others will know the question is resolved :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.