Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

452
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda