好的,我有以下代码
router.route('/getParkData/:parkLocationId').get(function(req, res){
var id = req.params.parkLocationId;
var parkdata = {};
parkInfo(id).then(function(data){
if(data.parking_type == 'FREE')
{
var json = JSON.stringify({
"error" : null,
"result" : null,
"message" : "free",
"error_code" : null
});
res.end(json);
}
else
return getTwowheelers(id)
}).then(function(data){
if(data[0].parking_type)
{
parkdata.parkingType = data[0].parking_type;
}
else
{
parkdata.parkingType = "paid";
}
if(data.length > 0)
{
parkdata.tw = data[0].rate.tw[0];
}
else
{
parkdata.tw= 0;
}
return getFourwheelers(id);
}).then(function(data){
console.log(data.length);
if(data.length > 0)
{
parkdata.fw = data[0].rate.fw[0];
}
else
{
parkdata.fw = 0;
}
res.json(mResponse.response(null, parkdata, "Success",200));
}).catch(function(err){
res.json(mResponse.response(null, null, "No data!",500));
});
});
所以我通过检查条件并结束响应来快速解决问题。它工作正常,但我收到了这个错误。
Unhandled rejection Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (C:\zoyoapp\node_modules\express\lib\response.js:719:10)
所以res.end并没有结束执行。任何我可以使它不显示此错误的方式
答案 0 :(得分:2)
Error: Can't set headers after they are sent.
是因为您在承诺链的末尾再次发送响应。你可以通过拒绝来破解承诺链。
router.route('/getParkData/:parkLocationId').get(function(req, res) {
var id = req.params.parkLocationId;
var parkdata = {};
parkInfo(id).then(function(data) {
if (data.parking_type == 'FREE') {
return Promise.reject({
type:'FREE_USER'
data: JSON.stringify({
"error": null,
"result": null,
"message": "free",
"error_code": null
})
}); //rejecting this promise
} else {
return getTwowheelers(id);
}
}).then(function(data) {
if (data[0].parking_type) {
parkdata.parkingType = data[0].parking_type;
} else {
parkdata.parkingType = "paid";
}
if (data.length > 0) {
parkdata.tw = data[0].rate.tw[0];
} else {
parkdata.tw = 0;
}
return getFourwheelers(id);
}).then(function(data) {
console.log(data.length);
if (data.length > 0) {
parkdata.fw = data[0].rate.fw[0];
} else {
parkdata.fw = 0;
}
res.json(mResponse.response(null, parkdata, "Success", 200));
}).catch(function(err) {
if(err.type === 'FREE_USER'){
return res.send(err.data); // sending response only once
}
res.json(mResponse.response(null, null, "No data!", 500));
});
答案 1 :(得分:0)
当条件
if(data.parking_type == 'FREE')
是真的,它会用json响应
var json = JSON.stringify({
"error" : null,
"result" : null,
"message" : "free",
"error_code" : null
});
res.end(json);
但代码将在接下来的时间进一步执行,然后在最后它会找到命令
res.json(mResponse.response(null, parkdata, "Success",200));
尝试设置导致错误的标头。即你试图在res.end();
之后发送回复