【问题标题】:If/Else hangs when trying to respond with different valuesIf/Else 在尝试以不同的值响应时挂起
【发布时间】:2015-09-28 17:53:27
【问题描述】:

我有一个方法可以在文件中搜索一个术语,然后将整行作为 JSON 对象返回。出于某种原因,当我添加逻辑的else 部分时,我收到以下错误:

_http_outgoing.js:335
    throw new Error('Can\'t set headers after they are sent.');
      ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
    at ServerResponse.header (/home/vagrant/node_modules/express    /lib/response.js:718:10)
    at ServerResponse.contentType (/home/vagrant/node_modules/express/lib/response.js:551:15)
    at ServerResponse.send (/home/vagrant/node_modules/express/lib/response.js:138:14)
    at /home/vagrant/routes/service.js:18:13
    at /home/vagrant/model/instance_map.js:22:17
    at fs.js:334:14
    at FSReqWrap.oncomplete (fs.js:95:15)

如果我从下面删除 else 语句,它会起作用,除非路由不匹配,然后应用程序就会挂起,除非我添加超时:

exports.mapData = function(instance, instance_map) {

    //read the file and return the matched array
    fs.readFile(path.join(__dirname,'../instance-map'), 'utf8', function (err, data) {
        if (err) {
          return console.log(err);
        }

        for (line of splitFile(data))
            if(line.match(instance)) {

                // this is the asynchronous call
                instance_map(convertToJSON(line));

            } else {
                instance_map(instance);
            }

    })
}

在尝试调用res() 两次时,似乎经常弹出此错误,但我没有做类似的事情。不完全确定这个错误会发生在哪里。调用该方法的实际路由如下:

router.get('/mapinfo/:instance_id', function ( req, res, error) {
    file_map.mapData(req.params.instance_id, function (instance_map) {
        res.send(instance_map);
    });
});

想法是将最后一个参数与文件的内容匹配并返回json。我是 nodejs 的新手,所以我可能缺少一些简单的东西。

【问题讨论】:

    标签: javascript json node.js http


    【解决方案1】:

    您的 if...else 在 for 循环中。所以res.send()可能会被调用多次。

    【讨论】:

    • 好吧,我觉得自己很愚蠢哈哈。无论如何,我也在发送回复。我改变了它,所以 if/else 改变了方法范围内的变量。我想我对回调和看待代码的新方式非常着迷,以至于我并没有真正看在我的面前。
    【解决方案2】:

    当您进入 else 语句时,您会向回调函数发送“req.params.instance_id”。

    如果你在 req 中的 instance_id 是 Number 它将不起作用:

    "body 参数可以是 Buffer 对象、String、对象或 Array。"

    Express res.send

    正如 Igal 所说,你有 for 循环,你的 for 循环看起来很奇怪。

    【讨论】:

    • 是的,我在阅读这篇文章后几乎立即意识到我的循环存在各种错误。应该早点发现
    猜你喜欢
    • 1970-01-01
    • 2011-08-10
    • 2014-08-22
    • 1970-01-01
    • 2012-07-05
    • 2018-01-25
    • 2016-03-21
    • 1970-01-01
    • 2022-07-13
    相关资源
    最近更新 更多