forEach是否在数组上异步?糖果是一系列糖果对象。
app.get('/api/:id',function(req, res){
console.log("Get candy");
var id = req.params.id;
candies.forEach( function(candy, index){
if(candy.id == id){
console.log("Candy found. Before return");
return res.json(candy);
console.log("Candy found. After return");
}
});
console.log("Print error message");
return res.json({error: "Candy not found"});
});
在控制台中我得到了
[nodemon] starting `node app.js`
listning on port 3000
Get candy
Candy found. Before return
Print error message
Error: Can't set headers after they are sent.
at ServerResponse.setHeader (_http_outgoing.js:367:11)
....
这是最近的变化吗?自从我完成了node.js
以来已经有一段时间了答案 0 :(得分:1)
您正在获得Can't set headers after they are sent.
例外,因为您尝试在candies.forEach
内再次(可能)返回一次响应,并再次返回路线的最后一行。另请注意,return
之后的任何代码都无法执行。
这里是如何重写它以避免错误的 -
app.get('/api/:id',function(req, res){
console.log("Get candy");
var id = req.params.id;
var foundCandy = false;
candies.forEach( function(candy, index){
if(candy.id == id){
foundCandy = true;
console.log("Candy found. Before return");
}
});
if (foundCandy) {
return res.json(candy);
} else {
return res.json({error: "Candy not found"});
}
});
答案 1 :(得分:1)
您可以使用Array.filter查找糖果。
app.get('/api/:id', function(req, res) {
console.log("Get candy");
var id = req.params.id;
var result = candies.filter(candy => candy.id == id);
if (result.length) {
return res.json(result[0]);
} else {
console.log("Print error message");
return res.json({
error: "Candy not found"
});
}
});