我有一个方法可以在文件中搜索一个术语,然后将整行作为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的新手,所以我可能会缺少一些简单的东西。
答案 0 :(得分:0)
当你进入else语句时,你会发送回你的回调函数" req.params.instance_id"。
如果req中的instance_id为Number,则无效:
" body参数可以是Buffer对象,String,对象或Array。"
正如Igal所说,你有for循环,你的for循环看起来很奇怪。
答案 1 :(得分:0)
你的if...else
在for循环中。因此可以多次调用res.send()
。