【问题标题】:TypeError: Cannot read properties of null (reading 'role')TypeError: Cannot read properties of null (reading \'role\')
【发布时间】:2022-12-26 15:53:37
【问题描述】:

I am trying to give special role to admin using a middleware customRole which checks the default role of user in the database and provide special administration for the user with admin role.

My controller code for userController is:

const User = require('../models/User')
//Other requires are present but not needed for this function.
.
.
.

exports.adminAllUser = BigPromise(async(req, res, next) => {
    const users = await User.find()

    res.status(200).json({
        success: true, 
        users,
    })
})

My middleware code for user is:

const User = require('../models/User')
const CustomError = require('../utils/customError')
.
.
.
exports.customRole = (...roles) => {
    return(req, res, next) => {
        if (!roles.includes(req.user.role)) {
            return next(new CustomError('You are not allowed for this resource', 403))
        }
        next()
    }
}

My user route is /admin/users and I am passing 3 functions to give power to admin when logged in.

const { adminAllUser } = require("../controllers/userController")
const { isLoggedIn, customRole } = require('../middleware/user')
.
.
.
router.route('/admin/users').get(isLoggedIn, customRole('admin'), adminAllUser)

The error I am receiving whenever I am giving a GET request to /admin/users with admin role:

TypeError: Cannot read properties of null (reading 'role')
    at C:\Users\****\Login API\middleware\user.js:24:38
    at Layer.handle [as handle_request] C:\Users\****\Login API\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\****\Login API\node_modules\express\lib\router\route.js:144:13)
    at C:\Users\****\Login API\middleware\user.js:19:9
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    If you debug your code you will find out that no value is passing into that role.

    debug here if (!roles.includes(req.user.role)) {

    【讨论】:

    • I have console.logged it and showing undefined. May I know what will be the reason for not passing this req.user.role value? It is there in the database, but couldn't retrieve it.
    • I think it is the spread operator not working correctly.
    • Can you please give me a code to avoid using spread operator in this case? I am just a beginner referring videos for learning, my instructor done like this and he didn't get any errors.
    【解决方案2】:

    Now i am facing the same error can you help me? @Aashiq Shajahan ?

    【讨论】:

    猜你喜欢
    • 2021-11-10
    • 2021-12-21
    • 2021-12-12
    • 1970-01-01
    • 2022-07-01
    • 2022-11-20
    • 2023-01-10
    • 2021-11-03
    • 2021-11-08
    相关资源
    最近更新 更多