Zain763
Zain763

Reputation: 77

Why does this NodeJS code return empty response object?

This is the code:

router.post("/form", async (req, res) => {
  try {
    let { name, email, password } = req.body;
    let user = await User.create({
      name,
      email,
      password,
    });

    if (!user) return res.status(501).send("Something went wrong");
    let token = await user.getSignedToken();
    console.log(token); //Server logs this

user.emailToken = await user.verifyEmail();// This property is not being added in the saved mongodb document. It should, but again idk why it's not

    await user.save({ validateBeforeSave: false });
    console.log(user); // Server doesn't log this
    const options = {
      expires: new Date(
        Date.now() + process.env.JWT_COOKIE_EXPIRE * 24 * 60 * 60 * 1000
      ),
    };
    console.log(options); // Server doesn't log this
    res.cookie("token", token, options);
    res.send("Check email for activation");
  } catch (ex) {
    res.send(ex);
  }
});

Below is the verifyEmail method (in userSchema.. I'm using mongoose):

userSchema.methods.verifyEmail = async function () {
  let emailToken = this._id + crypto.randomBytes(10).toString("hex");
  let emailTokenHashed = await crypto
    .createHash("sha256")
    .update(passwordToken)
    .digest("hex");
  this.emailToken = emailTokenHashed;

  return emailToken;
};

Now, it should send "Check email for activation", right? But, it's sending an empty response object. Also, if you see in the code, the server is logging only one console.log (i.e. the first console.log). But, it is sending a cookie (I checked via postman). So, what's the issue here?

Upvotes: 1

Views: 7100

Answers (1)

jfriend00
jfriend00

Reputation: 707148

This code sends res.send("Check email for activation"); or res.send(ex);. Since you say that:

console.log(options); // Server doesn't log this

then one of your await statements must be hitting a rejected promise and sending you to the catch. Add console.log(ex) right before res.send(ex) to see what the error is so you have this:

} catch (ex) {
    console.log("got error", ex);
    res.send(ex);
}

And, then see what you get in the log.

In general you never want to send an error object directly because most of its properties are non-enumerable so they won't get sent as JSON and that may make the error object completely empty when it gets converted to JSON and thus isn't useful to the client at all. Instead, log the error on your server and send a 500 status:

res.sendStatus(500);

Or, if you want to send an error object construct your own error object with regular, enumerable properties and send that.

Anyway, once you add the console.log(ex) to your server, it should tell you what the actual rejected promise is and that will show you what's going wrong with the request. ALWAYS log errors on the server to help you see and solve problems like this.

Upvotes: 1

Related Questions