首页 > 解决方案 > 为什么这个 NodeJS 代码返回空响应对象?

问题描述

这是代码:

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);
  }
});

下面是 verifyEmail 方法(在 userSchema 中。我使用的是猫鼬):

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;
};

现在,它应该发送“检查电子邮件以进行激活”,对吧?但是,它正在发送一个空的响应对象。此外,如果您在代码中看到,服务器只记录一个console.log(即第一个console.log)。但是,它正在发送一个 cookie(我通过邮递员检查过)。那么,这里有什么问题呢?

标签: node.jsexpress

解决方案


此代码发送res.send("Check email for activation");res.send(ex);。既然你这么说:

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

那么您的其中一个await陈述必须达到拒绝的承诺并将您发送到catch. console.log(ex)在之前添加res.send(ex)以查看错误是什么所以你有这个:

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

然后,看看你在日志中得到了什么。

通常,您永远不想直接发送错误对象,因为它的大多数属性都是不可枚举的,因此它们不会作为 JSON 发送,并且当错误对象转换为 JSON 时可能会使错误对象完全为,因此没有用对客户来说。相反,在您的服务器上记录错误并发送 500 状态:

res.sendStatus(500);

或者,如果您想发送一个错误对象,请使用常规的、可枚举的属性构造您自己的错误对象并发送它。

无论如何,一旦你将它添加console.log(ex)到你的服务器,它应该会告诉你实际被拒绝的承诺是什么,这会告诉你请求出了什么问题。始终在服务器上记录错误以帮助您查看和解决此类问题。


推荐阅读