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

453
Visualizações
Cannot read properties of undefined (reading 'split'), how to remove error

When adding some fields to the page (from the client side), an error occurs: Cannot read properties of undefined (reading 'split'). Occurs in this code snippet const jwt = require('jsonwebtoken');

module.exports = function(role) {
    return function (req, res, next) {
        if (req.method === "OPTIONS") {
            next();
        }
        try {
            const token = req.headers.authorization.split(' ')[1];
            if (!token) {
                return res.status(401).json({message: "Not authorized"});
            }
            const decoded = jwt.verify(token, process.env.SECRET_KEY);
            if (decoded.role !== role) {
                return res.status(403).json({message: "No access"});
            }
            req.user = decoded;
            next();
        } catch (e) {
            console.log(e.message); //error message here
            res.status(401).json({message: "Not authorized"});
        }
    };
}

Moreover, if you add it from the server side (for example, in postman), then everything works well. Where is the mistake?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This simply means that req.headers.authorization value is not a string (or most likely it has the value: undefined. You should check first if the value is set (and that it is valid i.e a string) before calling split

if(req.headers.authorization) { const token = req.headers.authorization.split(' ')[1]; }

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