Express / NodeJS由http请求发送后无法发送标头

时间:2011-08-04 03:21:03

标签: http node.js request express

第一次使用NodeJS(是的,它很棒)并且也使用Express。让网络应用程序/服务工作得很好但是在尝试发出多个http请求时我遇到了问题。这是一个关于应用程序如何导致2个http请求的视频 - http://screencast.com/t/yFKdIajs0XD - 正如您所看到的,我点击“文章”它会加载RSS Feed,然后点击视频并加载youtube Feed - 两者都运行正常但是之后第二次调用使它抛出异常。当我使用节点的http模块尝试两个单独的http请求时,我得到以下内容:

http.js:527
throw new Error("Can't set headers after they are sent.");
      ^

Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/Users/rickblalock/node/auti_node/node_modules/express/node_modules/connect/lib/patch.js:47:22)
at /Users/rickblalock/node/auti_node/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js:72:19
at [object Object].<anonymous> (fs.js:107:5)
at [object Object].emit (events.js:61:17)
at afterRead (fs.js:878:12)
at wrapper (fs.js:245:17)

此处提供示例代码: 使用我的控制器模块呈现请求 - http://pastie.org/2317698 其中一个标签(文章标签) - 视频代码相同而不是引用视频供稿:http://pastie.org/2317731

1 个答案:

答案 0 :(得分:3)

尝试使用“结束”事件而非“数据”,如下所示:

var data = "";

app.get('/', function(req, res){

    var options = {
          host: 'http://www.engadget.com',
          path: '/rss.xml',
          method: 'GET'
        };

    if (data === "") {
        var myReq = http.request(options, function(myRes) {
            myRes.setEncoding('utf8');

            myRes.on('data', function(chunk) {
                console.log("request on data ");
                data += chunk;
            });

            myRes.on('end', function () {
                console.log("request on END");
                res.render('index', {
                    title: 'Express',
                    data: data
                });
            });
        });

        myReq.write('data\n');
        myReq.end();
    }
    else {
        res.render('index', {
            title: 'Express',
            data: data
        });
    }
});

旧回答

我也认为这是罪魁祸首:

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function(chunk) {
      parseArticle(chunk);
    });
});
req.write('data\n');
req.end();

第一行是异步的,因此在执行req.write()req.end()后调用回调内的所有内容 将这两行放入回调中。