Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

140
Visualizações
"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')"
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda