Node.js NodeJS/MongoDB-错误:Can';t在发送邮件后设置邮件头
我得到了这个助手函数:Node.js NodeJS/MongoDB-错误:Can';t在发送邮件后设置邮件头,node.js,mongodb,Node.js,Mongodb,我得到了这个助手函数: const Account = require('../models/account'); exports.sendInvites = (accountIds, invite, callback) => { if (!accountIds) { callback('No account ids provided', null, null); return; } accountIds.forEach((id) => {
const Account = require('../models/account');
exports.sendInvites = (accountIds, invite, callback) => {
if (!accountIds) {
callback('No account ids provided', null, null);
return;
}
accountIds.forEach((id) => {
Account.findOneAndUpdate({_id: id}, {$push: {organisationInvites: invite}}, callback);
});
};
那么我有这个路线:
router.post('/organisations', auth.verifyToken, (req, res, next) => {
const organisation = new Organisation({
name: req.body.name,
email: req.body.email,
admins: [req.body.createdBy],
createdBy: req.body.createdBy
});
organisation.save((err, organisation) => {
if (err) {
return res.status(500).json({
error: err,
data: null
});
}
organisationUtils.sendInvites(req.body.invites, {
inviter: req.body.createdBy,
organisation: organisation._id
}, (err, account, response) => {
if (err) {
return res.status(500).json({
error: err,
data: null
});
}
res.json({
error: null,
data: organisation
});
});
});
});
我收到一个错误:发送头后无法设置头。
错误
res.json({
error: null,
data: organisation
});
但我不明白为什么会这样。我试着在这里查看被接受的答案,做了一些挖掘,但找不到任何具体的原因,仍然在我上面的特定示例中发生了什么。有什么想法吗?您多次调用回调,因此
res.json
多次调用。从所有数据库请求中收集数据,然后执行唯一的res.json
accountIds.forEach((id) => {
Account.findOneAndUpdate(
{_id: id},
{$push: {organisationInvites: invite}},
callback,
);
});
比如:
var allData = [];
var nbRequestDone = 0;
var waitAllCallback = function (data, err) {
if (err) {
callback(err);
nbRequestDone = accountIds.length;
return;
}
nbRequestDone += 1;
allData.push(data);
if (nbRequestDone === accountIds.length) {
callback(false, allData);
}
};
accountIds.forEach((id) => {
Account.findOneAndUpdate(..., waitAllCallback);
});
本视频介绍有关“错误:发送邮件后无法设置邮件头”的错误。
在视频的摘要中,当代码中有额外的回调时,就会出现此错误。希望这有帮助。我也为这件事挣扎了很长一段时间 无法在循环中使用回调。必须在完成所有db操作后调用回调。如果确实要多次使用回调,请使用异步库<代码>https://caolan.github.io/async/docs.html因此,我尝试了它,但有时请求不会向客户端返回响应。知道为什么吗?你检查过错误是否被返回了吗?(第一个参数)我想我已经解决了。有一个条件检查失败了一半的时间,原因不明。谢谢。虽然这个链接可以回答这个问题,但最好在这里包含,并提供链接供参考。如果链接页面发生更改,则仅链接的答案可能无效。