【问题标题】:Middleware Function That Checks If User Is Authenticated检查用户是否经过身份验证的中间件功能
【发布时间】:2021-01-05 01:43:51
【问题描述】:

我有一个 Express 中间件功能,用于检查用户是否已通过身份验证。如果他们没有通过身份验证,我想向我的前端发送一些 JSON 来说明这一点,但如果是,我想在这条路线上继续我的正常功能。

例如,

const checkAuth = (req, res, next) => {
    if (!authenticated){
        res.status(401).send("You are not authorized to view this content");
    }
    next();
}


app.get('/protectedRoute', checkAuth, (req, res) => {
    // SOME OTHER DATABASE STUFF HERE WHICH RESULTS IN VARIABLE "data"
    res.json({msg: data});
});

但是,我在尝试返回 json 时收到此错误:

Cannot set headers after they are sent to client

我该怎么做?谢谢!

【问题讨论】:

    标签: node.js express middleware


    【解决方案1】:

    检测到请求未通过身份验证时停止请求。

    if true 块中添加return 关键字

    const checkAuth = (req, res, next) => {
        if (!authenticated){
            return res.status(401).send("You are not authorized to view this content");
        }
        next();
    }
    

    【讨论】:

      【解决方案2】:

      那是因为您正在执行next(),即使用户未通过身份验证检查。这会导致您在发送 401 响应后执行其他代码,这就是错误所抱怨的。

      只需添加一个else

      const checkAuth = (req, res, next) => {
          if (!authenticated){
              res.status(401).send("You are not authorized to view this content");
          }
          else {
              next();
          }
      }
      

      另外,有些人更喜欢使用return 来打断流程:

          if (!authenticated){
              res.status(401).send("You are not authorized to view this content");
              return;
          }
          next();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-09
        • 1970-01-01
        • 2018-09-15
        • 1970-01-01
        相关资源
        最近更新 更多