【问题标题】:Getting error '_http_outgoing.js:335' while sending API response from backend to frontend从后端向前端发送 API 响应时出现错误“_http_outgoing.js:335”
【发布时间】:2015-08-15 00:09:46
【问题描述】:

在我的 Angular/Node 应用程序中,我在 Node.js 后端调用了 3rd party API,并且在向 Angular.js 前端发送数据时遇到了错误。

这是我的Node.js 代码的相关部分:

app.use('/callApi', function(req, res, next) {

    var result;

    var url = 'http://someApi.com/someData';

    http.get(url, function(resp) {
        var body = '';

        resp.on('data', function(chunk) {
            body += chunk;
            console.log("Got body: " + body);
        });

        resp.on('end', function() {
            console.log("Got response: " + body);   // WORKS!

            // res.setHeader("Content-Type", "text/html");
            // res.send(body);                      // DOES NOT WORK!

            sendResult(body);                       // DOES NOT WORK!
        });
    }).on('error', function(e) {
        console.log("Got error: ", e);
    });

    function sendResult(result){
        res.send(result);
    };

    res.send('about done');                         // WORKS!

    next();
});

在 Node.js 终端中,我看到响应后出现错误:

_http_outgoing.js:335

... Node.js 进程被终止。

我在我的项目中的任何地方都没有看到这个 _http_outgoing.js 文件。

谁能指点我正确的方向?

【问题讨论】:

  • 错误应该不仅仅是内置的文件名和行号,例如实际的异常消息和更多的堆栈跟踪行。您是否尝试添加错误处理中间件?
  • 另外,你使用的是什么版本的节点?
  • @mscdex 我希望这个错误还有更多。如何添加错误处理中间件?我正在使用node v0.12.4
  • 你通过添加一个带有 4 个参数的中间件来添加一个:app.use(function(err, req, res, next) { console.error(err.stack) })

标签: angularjs node.js http get


【解决方案1】:

FWIW 实际错误是Can't set headers after they are sent.

问题是您在路由处理程序的末尾调用next()。因此,其他一些中间件或路由处理程序也在处理请求,并且在您的 http.get() 完成之前已经发送了响应。

删除 next() 并从 http.get() 内部响应请求应该可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-02
    • 2013-01-30
    • 2017-12-01
    • 2015-10-25
    • 2019-07-17
    • 2021-09-23
    • 1970-01-01
    • 2014-08-10
    相关资源
    最近更新 更多