Javascript 尝试使用不同的值响应时,If/Else挂起
我有一个方法,它在文件中搜索一个术语,然后将整行作为JSON对象返回。出于某种原因,当我添加逻辑的else部分时,我得到以下错误:Javascript 尝试使用不同的值响应时,If/Else挂起,javascript,json,node.js,http,Javascript,Json,Node.js,Http,我有一个方法,它在文件中搜索一个术语,然后将整行作为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.setHea
_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的新手,所以我可能缺少一些简单的东西。当进入else语句时,向回调函数发送req.params.instance_id 如果您的req中的实例id是数字,则它将不起作用: body参数可以是缓冲区对象、字符串、对象或数组
正如Igal所说,你有for循环,而你的for循环看起来很奇怪。你的if…else在for循环中。所以res.send可能会被打好几次。我觉得自己很愚蠢,哈哈。不管发生什么事,我也在发送回复。我更改了它,以便if/else在方法范围内更改变量。我想我被回调和查看代码的新方式吸引住了,以至于我没有真正正视我的面前。是的,读了这篇文章后,我几乎立刻意识到我的循环有各种各样的错误。我应该早点发现的