【问题标题】:"Cannot read properties of null (reading 'role')"“无法读取 null 的属性(读取'角色')”
【发布时间】:2022-07-24 17:38:32
【问题描述】:

代码

这是我在 VS 代码中的代码,用于检查用户是管理员还是用户

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

    next();
  };
};

邮递员 API 中的错误

使用过的声明应该没问题我不知道这是什么问题

"success": false,
"message": "Cannot read properties of null (reading 'role')"

【问题讨论】:

  • 你是怎么设置用户的?
  • 根据错误,您正在尝试访问role 对象的role 属性。这意味着您的 user 对象正在获取空值。你从哪里得到user 对象?你是从身体上得到的,还是从其他地方得到的?

标签: javascript express postman


【解决方案1】:

根据您的描述,我假设您在req.user 上的user 对象为空,因此它会尝试读取空对象的role 属性。

现在,您可以在验证角色之前检查 null,这样 API 至少会返回正确的错误。 (例如见here

类似的东西(尚未测试代码):

if (null == req?.user?.role) {
    return next(new ErrorHandler(`Bad request`, 400));
}

但这仍然不能解决有效请求的问题。为此,我建议您向我们提供有关如何声明请求的更多信息。

【讨论】:

  • 这是我在我的用户模型架构 role: { type: String, default: "user", }, 中声明的默认角色,这是我在用户控制器中的用户 const user = await User.create({ name, email, password, avatar: { public_id: "this is a sample id", url: "profilepicUrl", }, }); 这是它在 mongodb 中的保存方式 name : "malek" email : "6pp@test.com" password : "$2a$10$8P9R2VjtDKf0b3EkukfSje7t3wswECEzdNAchsau17Kl79N.27RT." avatar : Object role : "user" 仍然不明白可悲的是这个问题。
  • @AdamThabet 我认为这些是测试记录,而不是您的真实凭据,但看到这样发布的密码和电子邮件我仍然感到不舒服^^。关于您的问题:1)您可以在控制器中设置断点以查看实际创建用户的天气。假设他这样做了(因为它的记录显然在数据库中),您可以 2)向我们展示您的邮递员请求(问题可能是无效/不完整的请求数据)或 3)您的后端 - 也可以使用断点进行测试 - 看看什么您实际收到(即可能存在编码/解码问题或其他问题)
【解决方案2】:

我知道你被困在哪里......

转到 auth.js 文件。在那里使用:

 req.user = await User.findById(decodedData.id);

而不是 ._id

【讨论】:

    猜你喜欢
    • 2020-05-27
    • 2022-01-14
    • 2021-02-26
    • 1970-01-01
    • 2021-03-02
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多