javascript - Express.js/while-else循环重定向问题

标签 javascript node.js express

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/

相关文章:

Javascript Titanium,循环标签仅显示数组中的最后一个数据

javascript - socket.io 连接事件不起作用,为什么?

node.js - 用于用户和管理员的 deserializeUser

javascript - 在没有 request 变量的情况下检索 Node js/express 中的 session 信息

ios - 在 iOS 中,http 204 响应返回空白页面,有办法阻止这种情况吗?

javascript - 未存储 SetCookie header

javascript - JQuery .attr 问题。 $ ('#id' ).attr ('value' );返回未定义

javascript - 指定的值 "undefined"不是有效数字

node.js - 如何使用VueJs添加img src属性

javascript - 使用 Express 和 NodeJS 构建 REST API 的最佳实践