I am using nodemailer to send email to the user but when I hit the api i get this error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I can't understand why
This is the route code:
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"})
};
Can anyone tell me why this is happening and how do I fix this
CodePudding user response:
res.send(STATUS_CODE).json()
is deprecated. See here for more information.
Instead, use the following:
res.status(200).json({message:"Verification link has been sent to your email. Please verify your email"}})
(Also see this)
CodePudding user response:
That's due to you used async and callback function together. As callback performs in parallel excution with async so it cause this issue.
Best way to do with less changes as below put inside else condition.
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" });
}else {
// 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.status(200).json({message:"Verification link has been sent to your email. Please verify your email"})
}
};