1

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.

msorr95
  • 81
  • 1
  • 10
  • 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*. – Molda Feb 25 '21 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 – msorr95 Feb 25 '21 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. – Molda Feb 25 '21 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! – msorr95 Feb 26 '21 at 08:51

2 Answers2

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

Zavael
  • 2,383
  • 1
  • 32
  • 44
  • 1
    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. – msorr95 Feb 26 '21 at 08:50
  • 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` – Zavael Feb 26 '21 at 09:25
  • 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! – msorr95 Feb 26 '21 at 20:09
  • happy to hear that you solved your problem, feel free to accept an answer so others will know the question is resolved :) – Zavael Apr 14 '21 at 10:02
0

In order to solve the issue I removed the error middleware and I also removed everything that was into the if block and replaced it with return res.status(401).json({ message: 'invalid password' });. To be honest, I don't know why one code works and the other not since it is pretty much the same code.. I hope it will help somebody!

msorr95
  • 81
  • 1
  • 10