我正在使用nodemailer发送电子邮件给用户,但当我点击API时,我得到这个错误:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
我不明白为什么这是路线代码:
exports.create = async (req, res) => {
// Check if the attendee already exists
let user = await Attendee.findOne({ email: req.body.email });
if (user) {
return res
.status(400)
.json({ error: "An attendee with this email already exists" });
}
// sending verification link to the user
const mailData = {
from: process.env.USER_ID,
to: req.body.email,
subject: "Email Verification link",
text: `Click on the link and verify your email`,
// verification link
html: `<a href="localhost:8000/api/verify">Click here to verify</a>`,
};
// sending the email
transporter.sendMail(mailData, (error, info) => {
if (error) console.log(error);
console.log("Email Sent Successfully");
});
res.send(200).json({message:"Verification link has been sent to your email. Please verify your email"})
};
有人能告诉我为什么会发生这种情况吗?我该如何解决这个问题
2条答案
按热度按时间92dk7w1h1#
这是因为你同时使用了异步和回调函数。因为回调函数和异步函数并行执行,所以导致了这个问题。
最好的方法做较少的变化,如下所示,放在else条件。
ccgok5k52#
已弃用。有关详细信息,请参阅此处。
请改为使用以下命令:
(Also见此)