i want to reset password with token but => SyntaxError: await is only valid in async function
i want to reset password with token but => SyntaxError: await is only valid in async function
我想使用 sendgrid 和 nodemailer 发送邮件,但是 => 语法错误: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({
我想使用 sendgrid 和 nodemailer 发送邮件,但是 => 语法错误: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({