发送到客户端后无法设置标头”"/>
Express 应用程序出现错误“发送到客户端后无法设置标头”
我确实有意返回(因此 userExists 变量为 True)。 我多次遇到这个错误,但我不明白它是如何生成的
但是在 catch 块上,终端指针指向 return res.status(500).json({ 行。但我确信这是因为我在表单中使用了现有电子邮件
商店_用户代码:
const STORE_USER = async (req, res) => {
try {
const {
name,
surname,
email,
password,
phone,
country,
city,
address,
zip,
dob,
gender,
} = req.body;
await prisma.$transaction(async (tx) => {
const userExists = await tx.user.findFirst({
where: {
email,
},
});
if (userExists) { // userExists is True, so I guess it returned this
return res.status(409).json({
success: false,
message: "User already exist",
code: "B00001",
});
}
const password_hashed = await bcrypt.hash(password, 10);
const user = await tx.user.create({
data: {
name,
surname,
email,
password: password_hashed,
gender,
phone,
address,
zip,
},
});
const token = crypto.randomBytes(30).toString("hex");
await tx.verify_Account.create({
data: {
Users: {
connect: {
id: user.id,
},
},
token,
},
});
const romeTimezone = "Europe/Rome";
const currentDateTimeInRome = utcToZonedTime(new Date(), romeTimezone);
// Add 2 hours to the current date and time in Rome
const newDateTimeInRome = addHours(currentDateTimeInRome, 2);
// Format the date in the desired format (dd/mm/yyyy hh:mm)
const dateFormat = "dd/MM/yyyy HH:mm";
const token_expiration_datetime = format(newDateTimeInRome, dateFormat, {
timeZone: romeTimezone,
});
sendEmailRegistration( //Is an async Function that in //success return res.status with json
email,
name,
surname,
token,
token_expiration_datetime
);
});
return res.status(200).json({
success: true,
});
} catch (error) {
console.log(error);
return res.status(500).json({
success: false,
code: "A00010",
});
}
};
发送邮件注册码:
const sendEmailRegistration = async (
email,
name,
surname,
token,
token_expiration_datetime
) => {
// Create a transporter object using Gmail SMTP transport
const transporter = nodemailer.createTransport({
service: process.env.EMAIL_SERVICE,
auth: {
user: process.env.EMAIL_USERNAME,
pass: process.env.EMAIL_PASSWORD,
},
});
const currentYear = new Date().getFullYear();
const URL = `${process.env.FRONTEND_URL}/verify_account?token=${token}`;
subject = "Test- Test";
html = `
<div>
Test
</div>
`;
// Define the email options
const mailOptions = {
from: process.env.EMAIL_USERNAME,
to: process.env.IS_PRODUCTION ? email : "[email protected]",
subject: subject,
html: html,
};
// Send the email
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log("Error occurred:", error.message);
return res.status(500).json({ message: "Error occurred" });
} else {
console.log("Email sent successfully!", info.response);
return res.status(200).json({ message: "Email sent successfully!" });
}
});
};
有人可以解释一下这个错误是如何发生的吗?
回答如下:据我了解,当多次向客户端发送响应时会发生这种情况。例如,res.status 和 res.send。
更多推荐
Express 应用程序出现错误“发送到客户端后无法设置标头”
发布评论