【问题标题】:postman error cannot read property role of null邮递员错误无法读取 null 的属性角色
【发布时间】:2021-12-13 11:00:33
【问题描述】:
exports.authorizeRoles = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return next(
        new ErrorHander(
          `Role: ${req.user.role} is not allowed to access this resouce `,
          403
        )
      );
    }

    next();
  };
};

【问题讨论】:

  • 看看你是如何使用它会很有帮助
  • 帮助解决这个问题
  • 欢迎来到 Stack Overflow。请添加有关您的代码的更多详细信息,一些有关您正在尝试做什么以及卡在哪里的 cmets。

标签: javascript postman


【解决方案1】:

错误消息显示Cannot read property role of null,这意味着req.usernull。您需要了解应该如何填写请求中的 user 对象。但如果它可能丢失是有效的,您可以像这样更改您的代码,它应该会更好地工作:

exports.authorizeRoles = (...roles) => {
  return (req, res, next) => {
    if (!req.user || !roles.includes(req.user.role)) {
      return next(
        new ErrorHander(
          `Role: ${req.user ? req.user.role : 'undefined'} is not allowed to access this resource `,
          403
        )
      );
    }

    next();
  };
};

【讨论】:

  • "success": false, "message": "Role: undefined is not allowed to access this resource"
  • 很好 - 如果请求中没有提供角色,那么这是正确的消息。如果您希望角色出现,那么您需要弄清楚如何定义 req.user 对象并包含正确的“角色”值。
  • 我们如何了解
  • 如果您询问如何了解 req.user 对象是如何创建的,这将取决于您的服务器接收请求以及它如何进行用户管理。这超出了您的问题范围,具体到您的实施。
猜你喜欢
  • 2022-07-24
  • 2020-05-27
  • 1970-01-01
  • 2022-01-14
  • 2021-02-26
  • 1970-01-01
  • 2021-03-02
  • 2021-07-18
  • 2022-01-18
相关资源
最近更新 更多