3

I´m building an express router that uses mongoose to access the database. My current problem relies on this piece of code:

app.use("/authreset", (req, res) => {
    authenticator
        .resetPassword(
            req.body.username,
            req.body.password,
            req.body.token,
            req.body.type
        )
        .then((response, error) => {
            if (error) throw new Error(error);

            console.log('*****************');
            console.log(response);

            if (!response) {
                res.sendStatus(401);
                return;
            }
        })
        .catch(error => {
            console.log('*****************');
            console.log(error);
            if (error) throw new Error(error);
        });

});

resetPassword uses the following mongoose call:

return UserModel
    .findByIdAndUpdate(user.id, data, { new: true })
    .exec();

For some reason, my route is being called and the response is fine (checked on console.log(response) inside promise).

My problem is that the response is never sent back to the client, that times out the fetch call.

Why is my promise not returning data?

halfer
  • 18,701
  • 13
  • 79
  • 158
Mendes
  • 13,757
  • 24
  • 122
  • 217
  • which promise is meant to return data, and where is it meant to return data to? - can't see anything returning data, nor even sending data in a response in the code you posted – Jaromanda X Feb 24 '18 at 05:21

1 Answers1

3

Uh, you log the response, but you never send it (or at least respond with a status code)?

Your code should look more like

app.use("/authreset", (req, res) => {
    authenticator.resetPassword(
        req.body.username,
        req.body.password,
        req.body.token,
        req.body.type
    ).then(response => {
        console.log(response);

        if (!response) {
            return res.sendStatus(401);
        } else {
            return res.sendStatus(200); // <<<
        }
    }, error => {
        console.log(error);
        return res.sendStatus(500);
    });
});

Notice that the then callback never gets called with more than one argument, so that error you were checking for cannot happen. In the catch handler, you should never rethrow an error if it doesn't get handled further down. Also I changed .then(…).catch(…) to the more fitting .then(…, …).

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • In fact I don´t need the reponse on the client, just the status. 401 failed, 200 succeeded. I removed the `res.send(response)` and my client is still stuck... – Mendes Feb 24 '18 at 05:25
  • Nothing, but I got the problem. I need `return res.sendStatus(200)` or whatever. I will edit your code. Thanks for helping. – Mendes Feb 24 '18 at 05:35
  • Perhaps a little explanation to go along with the code? – jfriend00 Feb 24 '18 at 06:46
  • @jfriend00 Ah, the OPs edit removed the main part of my explanation, didn't notice that – Bergi Feb 24 '18 at 07:18