• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

298
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?

almost 3 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]; }

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda