我读取json文件以使用req.params进行查询,我想返回res.json,但是我从express.js中得到了错误
_http_outgoing.js:482
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
在route.js中
module.exports = (app) => {
app.get('/find/:province', province.find);
}
在controller.js中
exports.find = function (req, res) {
fs.readFile('./app/models/province_file.json', function(err, provinces){
if (err) throw err;
let obj_provinces = JSON.parse(provinces);
let province = req.params.province;
for (var i = 0; i < obj_provinces.features.length; i++) {
if (obj_provinces.features[i].properties.tb_tn == province) {
let obj_result = obj_provinces.features[i].properties;
console.log(obj_result);
res.json(obj_result);
}
}
});
}
运行代码时出现错误
_http_outgoing.js:482
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:482:11)
at /Users/workspace/app/controllers/controller.js:87:13
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:54:3)
答案 0 :(得分:1)
请勿在for循环中调用res.json(obj_result);
,让您的循环完成工作,然后调用
res.json(obj_result);
;
在if
res.json(obj_result)
中被调用不止一次,这就是您收到此错误的原因。
最佳实践是在执行执行过程中使用return
,以确保执行在此时结束。
return res.json(obj_result);