在没有附加res语句的情况下发送标头后,无法设置标头(Can't set headers after they are sent without additional res statements)
使用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); }); }); }); }); }这会触发Error: Can't set headers after they are sent. 。 这里有趣的是,这个错误并不总是被触发 - 一切都运行良好~30分钟前。
此控制器中的任何其他位置都没有其他return res.x语句。
Using 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.. The interesting thing here is that this error isn't triggered always - everything worked fine ~30 minutes ago.
There's no other return res.x statement anywhere else in this controller.
最满意答案
您需要先安装async库。
npm install async --save
然后,您可以使用以下代码
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); }); });我没有测试过代码,但它应该可以正常工作。
You need to install the async library first.
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.
更多推荐
发布评论