'"Cannot read properties of null (reading 'role')"
Code
this is my code in VS code to check if the user is an admin or a user
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();
};
};
Error in postman API
the used declaration should be fine i don't know what's this problem
"success": false,
"message": "Cannot read properties of null (reading 'role')"
Solution 1:[1]
Based on your description, I assume your user object on req.user is null, therefor it tries reading the property role of a null object.
Now, you can just check for null before validating the role, this way the API will at least return the correct error. (e.g. see here)
Something along the lines of (haven't tested the code):
if (null == req?.user?.role) {
return next(new ErrorHandler(`Bad request`, 400));
}
But that still doesn't solve the issue for a valid request. For that I suggest you give us some more information on how you declare the request.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
