无法弄清楚为什么我不断收到[ERR
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
我看过其他有关同一问题的文章,但是我无法弄清楚如何解决我的问题。我有这样的代码来处理发布请求:
router.post('/', function(req, res) {
var movies = JSON.parse(fs.readFileSync('movies.json'));
var title = req.body.title;
movies.forEach(function(movie) {
if (title == movie.title) {
return res.render('movie', { watched: false });
} else {
return res.render('movie', { watched: true });
}
});
});
[我知道问题是由于res.render()
在那儿两次,但是即使使用return
语句,它仍然给我同样的错误,因此我很难理解它是如何两次发送的。由于return
关键字,它不应该只发送一次吗?
此外,如果我这样修改我的代码:
router.post('/', function(req, res) {
var movies = JSON.parse(fs.readFileSync('movies.json'));
var title = req.body.title;
movies.forEach(function(movie) {
if (title == movie.title) {
return res.render('movie', { watched: false });
}
});
res.render('movie', { watched: true});
});
然后,仅当if语句为false时,我才会收到错误。为什么会这样?
回答如下:您正在for循环中返回,因此每次都会发送
如下修改您的代码
router.post('/', function(req, res) {
var movies = JSON.parse(fs.readFileSync('movies.json'));
var title = req.body.title;
var counter =0;
var arr = [];
movies.forEach(function(movie) {
if (title == movie.title) {
arr.push({ watched: false , movieId:id})
} else {
arr.push({ watched: true , movieId:id})
}
counter++;
if(counter == movies.length){
return res.send({'movie':arr});
}
});
});