res.send() - 在发送标题后无法设置标题

时间:2017-06-21 08:51:19

标签: node.js api express

我正在使用Node js创建API,我遇到了多个参数api的问题。我从couchbase获取了多个文档。 API返回多个JSON文档,但在此之后,程序崩溃。我只打了一次res.send()。我不明白我哪里出错了。这是我的API:

router.get("/employee/collectinsert/:_startdate/:_enddate", function(req, res, next){

var startDate = moment(req.params._startdate);
var endDate = moment(req.params._enddate);
var daysOfYear = [];
for(var date = moment(startDate); date.diff(endDate,'days') < 1; date.add(1, 'days')){
    daysOfYear.push(formatDate(date));
}

bucket.getMulti(daysOfYear,function(err, results){
    if(err) throw err;

    for(var key in results) {
        if(results.hasOwnProperty(key)) {
            if(results[key].error) {
                console.log("`" + key + "`: " + JSON.stringify(results[key]));
            }
            res.send(results);
        }
    }
    process.exit(0);
});

});

我收到了这个错误:

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
    at ServerResponse.header (C:\Users\ekaplan\Desktop\dashboard\node_modules\express\lib\response.js:730:10)
    at ServerResponse.send (C:\Users\ekaplan\Desktop\dashboard\node_modules\express\lib\response.js:170:12)
    at C:\Users\ekaplan\Desktop\dashboard\api\employee.js:53:21
    at C:\Users\ekaplan\Desktop\dashboard\node_modules\couchbase\lib\bucket.js:1280:9

3 个答案:

答案 0 :(得分:4)

你在for循环中多次调用res.send()。

将其移出循环:

bucket.getMulti(daysOfYear,function(err, results){
    if(err) throw err;

    for(var key in results) {
        if(results.hasOwnProperty(key)) {
            if(results[key].error) {
                console.log("`" + key + "`: " + JSON.stringify(results[key]));
            }
        }
    }

    res.send(results); // called once when for loop has finished
});

答案 1 :(得分:1)

您的res.send处于循环中,您只能发送一个回复。

你可能想这样做:

bucket.getMulti(daysOfYear,function(err, results){
    if(err) throw err;

    for(var key in results) {
        if(results.hasOwnProperty(key)) {
            if(results[key].error) {
               console.log("`" + key + "`: " + JSON.stringify(results[key]));
            }

        }
    }
    res.send(results);
}

答案 2 :(得分:0)

因为首先你需要像res.header("Access-Control-Allow-Origin", "*");那样设置标题,而不是像@ Stretch所说的那样发送一个标题。