Postman 错误,无法读取空的属性角色

vpfxa7rd  于 2022-11-07  发布在  Postman
关注(0)|答案(2)|浏览(349)
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();
  };
};
unhi4e5o

unhi4e5o1#

错误消息显示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();
  };
};
8yoxcaq7

8yoxcaq72#

如果是,则返回一个新的消息。
请求用户=等待用户.findById(解码数据._id);
下一个(); });
将上面的代码替换为
如果是,则返回一个新的消息。
用户decodedData.id:
下一个(); });

相关问题