express 中是否有任何功能可以在不进一步执行的情况下结束 express 中的特定路由方法?

Is there any function in express to end a particular routing method in express without executing further?

所以我在这里有我的 post 路线,我想做的是检查用户是否满足在 body 中提供数据的所有条件,我通过添加一个if 块检查是否有错误

router.post("/", (req, res) => {

  if(req.body.age < 24) {
    res.send("You are too young")
    // I want it to end here
  }

  // further logic
  console.log('still executing')

}

如果不满足条件,它会进一步移动,尽管如果满足条件,发送响应后仍在执行进一步的逻辑,我希望它结束​​,这会给我带来更多问题,因为我有其他响应当输入正常时

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader 

为了解决这个问题,我已经尝试但没有奏效的是

router.post("/", (req, res) => {

  if(req.body.age < 24) {
    res.send("You are too young")
    res.end();
    // I want it to end here
  }

  // further logic
}

也试过直接结束

 if(req.body.age < 24) {
    res.end("You are too young")
    // I want it to end here
  }

有效的方法是返回并关闭函数本身

 if(req.body.age < 24) {
    res.end("You are too young")
    return;
    // it ends here
  }
 // does not execute after return statement

所以我想知道是否有快速的方式来做到这一点?同样阅读 res.end 也没有多大意义,因为它应该按照文档所述结束响应,但是我的其他 res.send 是否会发起新响应?和 create cannot set headers 问题 ?

不,没有特定的 'Express way' 可以做到这一点。在 Express 中,Response.end() 不是一个很好的做法,您应该始终回复请求。我会这样做:

router.post("/", (req, res) => {
  if (req.body.age < 24) return res.status(403).send("You are too young"); // 403 => Forbidden. If you don't know what error code you should use, 400 always works.
  // Here, req.body.age >= 24
}

我添加了.status(403)来表示错误不是来自服务器,而是来自客户端输入;在这种情况下,他们的访问权限是 Forbidden。 (HTTP code cheatsheet here,以后说不定会有用)否则默认就是200,就说明一切正常,这不是你想做的。 在我上面的代码片段中,请求得到了答复,所以一切都很好,Response.end() 将毫无用处。我认为这是完成这项工作的最简洁的方法(另外,最好不要使用空 return)。希望我有所帮助!