【发布时间】:2023-03-14 21:26:01
【问题描述】:
我有一个返回状态和一些 JSON 的简单函数。 通过表单输入,我将用户数据保存到 Db 中,同时通过 mailgun 将电子邮件消息发送给该用户。一切正常,但终端可能会出现错误 这是它的代码。
exports.signup = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({
// error: [errors.array()[0].msg || errors.array()[1].msg],
errors: [
{
msg: errors.array()[0].msg,
param: errors.array()[0].param,
},
],
});
}
const user = new User(req.body);
const { email, name } = req.body;
user.save((err, user) => {
if (err) {
return res.status(400).json({
err: "NOT able to save user in DB",
});
} else {
res.json({
name: user.name,
email: user.email,
id: user._id,
// password: user.password,
});
}
// mailgun - sending the mail
const data = {
from: "me@samples.mailgun.org",
to: email,
subject: "sending mail using mailgun",
text: "Testing some Mailgun awesomness!",
html: `<h1>Hey ${name} </h1>
<h2>Welcome , It's great to have you on board! </h2>`,
};
mg.messages().send(data, function (error, body) {
// console.log("mail send to user successfully");
if (error) {
return res.json({
error: error.message,
});
}
res.json({ message: "Email has been send successfully" });
});
});
};
这会引发错误:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
_http_outgoing.js:526
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:526:11)
at ServerResponse.header (C:\Users\Prathamesh\Desktop\College consession system\projBackend\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (C:\Users\Prathamesh\Desktop\College consession system\projBackend\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\Prathamesh\Desktop\College consession system\projBackend\node_modules\express\lib\response.js:267:15)
at Request.callback (C:\Users\Prathamesh\Desktop\College consession system\projBackend\controllers\auth.js:61:11)
at IncomingMessage.<anonymous> (C:\Users\Prathamesh\Desktop\College consession system\projBackend\node_modules\mailgun-js\lib\request.js:331:19)
at IncomingMessage.emit (events.js:323:22)
at endReadableNT (_stream_readable.js:1204:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
【问题讨论】:
标签: javascript reactjs express mongoose mailgun