【发布时间】:2020-07-30 20:51:21
【问题描述】:
这是代码:
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.. 我用的是 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;
};
现在,它应该发送“检查电子邮件以进行激活”,对吗?但是,它发送的是一个空的响应对象。此外,如果您在代码中看到,服务器只记录一个 console.log(即第一个 console.log)。但是,它正在发送一个 cookie(我通过邮递员检查过)。那么,这里有什么问题呢?
【问题讨论】:
-
创建哈希时不需要等待
crypto。 nodejs.org/dist/latest-v12.x/docs/api/… -
这不是您问题的答案,但为什么不在您的 Schema 方法中调用
this.save()而不是先调用user.emailToken = await user.verifyEmail()然后保存?或者你也可以只做await user.verifyEmail()而不将它设置为user.emailToken,因为它已经在Schema方法中设置了,不是吗?我在这里错过了什么吗? -
@jfriend00 不,它没有。它发送一个空对象作为响应