我仍然是node.js的新手,这里的数组包含一个id列表。当我从forEach循环发送响应时,我收到Error: Can't set headers after they are sent.
我用Google搜索但无法正确理解
array.forEach(function(data) {
db.collection.find({
_id: mongoskin.helper.toObjectID(data)
}).toArray(function(err, data1) {
if (err) return next(err);
console.log(data1);
res.send(data1);
})
})
答案 0 :(得分:3)
由于循环,您的代码多次调用res.send
;你不能这样做
res.send
是一个可以通过多种方式调用的重载函数,但无论如何使用它,它都会设置标头并发送响应。可以把它想象成一个一体化的,试图成为智能一体的功能。
// not actual source code!
// just imagine res.send kinda like this
function send(body, headers, status) {
res.setHeaders(headers);
res.statusCode = status;
res.write(body);
res.end();
}
但是,如果要分段编写响应,请改用res.write
方法。完成后,您必须致电res.end
。
res.setHeader(myHeaders);
myArray.forEach(
//...
res.write(something);
);
res.end();
答案 1 :(得分:0)
当多次调用res.end()
时会发生这种情况。
res.send()
方法是一种简单的响应方式,无需指定要发送的数据类型但只能调用一次。
见express docs
这就是res.send()
方法结束的方式 - express source
// respond
this.end(head ? null : body);
return this;
答案 2 :(得分:0)
使用此代码,
var index = 0;
var object = [] // empty array
function find(){
if(array.length -1 >=index){
var data = array[index] ;
db.collection.find({
_id: mongoskin.helper.toObjectID(data)
}).toArray(function(err, data1) {
if (err) return next(err);
console.log(data1);
object.push(data1);
//res.send(data1);
index++;
find();
})
}else{
res.send(object);
}
}
在您的情况下,您正在发送响应数据,但您的阵列仍在处理。所以,一旦您的回复发送,您就无法再次发送。