我想用令牌重置密码,但=>语法错误:await 仅在异步函数中有效



我想使用sendgrid和nodemailer发送邮件,但=>SyntaxError:await仅在异步函数中有效

帮助我如何解决这个错误

`

const postReset = async (req, res, next) => {
//generate random token
crypto.randomBytes(32, (err, buffer) => {
if (err) {
console.log(err);
return res.redirect('/reset');
}
const token = buffer.toString('hex');
const user = await User.findOne({ email: req.body.email });
try {
user.resetToken = token;
user.resetTokenExpiration = Date.now() + 3600000;
//save updated user
const result = await user.save();
if (result) {
res.redirect('/');
await transporter.sendMail({
to: req.body.email,
from: 'Yo-books@yogi.com',
subject: 'Password reset',
html: `
<p>You requested a password reset</p>
<p>Click this <a href="http://localhost:3000/reset/${token}">link</a> to set a new password.</p>,
});
}
} catch (error) {
req.flash('error', 'No account with that email found.');
return res.redirect('/reset');
}
})
};
`

在父函数中添加async关键字,在本例中是crypto.randomBytes的回调。你的代码应该看起来像:

const postReset = async (req, res, next) => {
//generate random token
crypto.randomBytes(32, async (err, buffer) => {
// ...
await transporter.sendMail({

最新更新