[英]Can't set headers after they are sent without additional res statements
Using sailsjs v0.12.1 使用sailsjs v0.12.1
index: function(req, res) {
Customer.find().populate('projects').exec(function(err, customers) {
customers.forEach(function(customer, index) {
customer.projects.forEach(function(project, index) {
// Find project contributors and attach to project
ProjectContributor.find({
project: project.id
}).populate('user').exec(function(err, contributor) {
project.contributor = contributor;
return res.json(customers);
});
});
});
});
}
This triggers Error: Can't set headers after they are sent.
这将触发Error: Can't set headers after they are sent.
. 。 The interesting thing here is that this error isn't triggered always - everything worked fine ~30 minutes ago. 有趣的是,此错误并非总是会触发-大约30分钟前一切正常。
There's no other return res.x
statement anywhere else in this controller. 此控制器中的其他任何地方都没有其他return res.x
语句。
You need to install the async
library first. 您需要先安装async
库。
npm install async --save
Then you can use the following code 然后您可以使用以下代码
var async = require('async');
// ...
// ...
Customer.find().populate('projects').exec(function(err, customers) {
var tArray = [];
async.each(customers, function(customer, cb) {
var aCustomer = customer; // might want to deep copy it?
aCustomer.projects = [];
async.each(customer.projects, function(project, projectCB) {
ProjectContributor.find({
project: project.id
}).populate('user').exec(function(err, contributor) {
project.contributor = contributor;
aCustomer.projects.push(project);
projectCB();
});
}, function projectsDone(err) {
tArray.push(aCustomer);
cb();
});
}, function done(err) {
return res.json(tArray);
});
});
I haven't tested the code, but it should work just fine. 我没有测试代码,但是应该可以正常工作。
用异步库的每个函数(async.each)替换forEach语句。所有迭代结束后,将调用一个回调,然后在该回调中放置res.send() 更多信息
I think you just had to write your: 我想你只需要写你的:
return res.json(customers);
statement at the end of the forEach loop. 在forEach循环末尾的语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.