app.post('/process', function(request, response){
var i = 0;
while(i < data.length){
if(data[i].condition1 == condition1 && data[i].condition2 == condition2){
response.redirect('/first_page');
}
i++;
}
response.redirect('/second_page');
}
我试图使如果条件 1 和条件 2 为真,则重定向到第一页。 如果为 false,则重定向到第二页。 但它不断发生错误。这是日志。
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
最佳答案
如果您想在数组数据中的任何项目符合条件时重定向到“first_page”,或者如果没有符合条件则重定向到“second_page”,
对代码最简单的更改是
app.post('/process', function(request, response) {
var i = 0;
while (i < data.length) {
if (data[i].condition1 == condition1 && data[i].condition2 == condition2) {
response.redirect('/first_page');
return; // done, no need to check any more of data
}
i++;
}
response.redirect('/second_page');
});
但是,将 Array#some
与 if/else 结合使用即可
app.post('/process', function(request, response) {
if (data.some(item => item.condition1 == condition1 && item.condition2 == condition2)) {
response.redirect('/first_page');
} else {
response.redirect('/second_page');
}
});
data.some
如果 data 中的任何一项符合条件,则返回 true,否则返回 false
就我个人而言,我更喜欢 Array.some 代码,因为它更整洁,并且对于正在发生的事情更明显
关于javascript - Express.js/while-else循环重定向问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58152538/