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?
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];
}