【问题标题】:node: res.locals is undefined?节点:res.locals 未定义?
【发布时间】:2020-07-31 21:14:52
【问题描述】:

我正在尝试进行身份验证中间件以检查收到的令牌是否有效并使用 res.locals 传递用户数据,但是当我尝试访问 res.local 时出现给定的错误。

authmiddleware : 检查令牌是否有效,如果用户存在则传递。

exports.authMiddleware = function (req, res, next) {
    const token = req.headers.authorization;

    if (token) {
        const user = parseToken(token);

        User.findById(user.userId, function (err, u) {
            if (err) {
                return res.status(422).send({
                    errors: normalizeErrors(err.errors)
                });
            }
            if (u !== null) {
                res.locals.user = u;
                console.log(res.locals)
                console.log(u)
                next();
            } else {
                return notAuthorized(res);
            }
        })
    } else {
        return notAuthorized(res);
    }
}

控制器从 re.locals 中提取用户,但错误是无法读取未定义的用户。

exports.changeAddress = function(req,res) {
    const {user} = req.locals;
}

【问题讨论】:

    标签: node.js api jwt


    【解决方案1】:

    这是因为req 对象上没有名为locals 的字段。 我假设changeAddress 是一个 POST 路由,locals 是从客户端作为 JSON 形式的 POST 请求正文发送的。

    如果是这种情况,您应该像这样访问localsreq.body.locals

    请记住,由于请求正文是 JSON,您需要 express 才能正确解析它。

    为此,需要安装body-parser中间件依赖,

    npm i body-parser

    然后将此中间件添加到您的 express 应用中,

    const bodyParser = require('body-parser')
    app.use(bodyParser.json())
    

    参考:https://expressjs.com/en/resources/middleware/body-parser.html

    【讨论】:

      猜你喜欢
      • 2014-01-14
      • 2015-04-11
      • 2021-12-05
      • 2022-01-05
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 2018-03-01
      相关资源
      最近更新 更多