【问题标题】:Express.js : about the behavior of next()Express.js:关于 next() 的行为
【发布时间】:2021-03-06 22:26:34
【问题描述】:

我正在学习使用 Express.js 创建 Web 应用程序。 在此过程中,我们尝试实现一项功能,以防止用户在未登录时访问某些页面。

//  teamController.redirectView : Redirect the screen according to res.locals.redirect
app.get('/user/:id/team/member', teamController.showMember, teamController.redirectView)
//  The following is a middleware function written in another file(teamController.js)
showMember: (req, res, next) => {

  //  I want to set the redirect to the '/login' and skip the following process when no user are logging in.
  if(!res.locals.loggedIn) {
    res.locals.redirect = 'login'
    next()
  }

  // access the property that is set only when the user logs in
  let userID = res.locals.currentUser.userID

  //  Other processes...

当我在用户未登录的情况下访问URI时,我确实被带到了登录页面,但是我在控制台中得到了以下错误。

TypeError: Cannot read property 'userID' of undefined
    at //  the position of 'let userID...'
Error occured: TypeError: Cannot read property 'userID' of undefined
    //  Abbreviated below...

这是否意味着执行 next() 不会像 'return' 那样跳过后面的过程? 或者是否存在导致此错误的致命错误? 你能帮帮我吗?

我本可以通过将所有后续进程包含在“else”中来避免该错误,但如果有更好的方法,如果您也能告诉我,我将不胜感激。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    这是否意味着执行 next() 不会像 'return' 那样跳过后面的过程?

    没错。单独调用next() 不会停止进一步的执行。
    这实际上是有意的,因为它允许额外的逻辑而不会使客户端等待更长时间(尤其是使用多个中间件时)。

    但是要解决您的问题,您可以将next()return 结合起来:

    if(!res.locals.loggedIn) {
      res.locals.redirect = 'login';
      return next();
    }
    

    这样您就不必在else 中扭曲以下所有代码。
    here 所述,这也是一种常见做法。

    【讨论】:

    • 感谢您的回答和帮助发布问题!我没有在中间件中返回某种值或函数的想法。中间件中“返回”的其他可能情况是什么?
    • @tayu 好吧,一个是您的中间件停止执行。另一个是您实际上将值(例如状态)返回给您的控制器。
    • @tayu 如果你的回答对你有帮助,请考虑accepting it :)
    • 对不起,很久没能退回你们的cmets了。谢谢您的答复。我会接受的!
    【解决方案2】:

    您必须使用return next() 否则代码在您调用next() 后继续执行

    【讨论】:

    • 感谢您的回答!代码现在按预期工作。我没有在中间件中返回值的想法。
    猜你喜欢
    • 2012-02-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多