【发布时间】: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