I’m new to use jwt library ..
So I made a login form and if it success it generates token and verify but it generates token and respond that token , but I can’t get that token in req.headers.authorization , i tried req.headers[‘authorization’] also , it shows undefined and I console logs req.headers it gives like host , connection , origin , accept , referrer , cookie …i try to add Authorization with token in my routes like this req.headers.authorization = token , it stores but can’t get it …
verify token.js
import { user } from './models/users.js';
export const verifyToken = async (req, res, next) => {
const authHeader = req.headers['authorization'];
if (!authHeader) {
return res.status(401).send('Token is missing');
}
const token = authHeader.split(' ')[1];
if (!token)
return res.status(401).send('Token is missing');
}
try {
jwt.verify(token, process.env.SECRET_KEY, async (err, decoded) => {
if (err) {
console.log('Token verification error:', err);
return res.status(403).send('Invalid token');
}
const user1 = await user.findOne({ id: decoded.id });
if (!user1) {
return res.status(404).send('User not found');
}
req.user = user1;
next();
});
} catch (e) {
console.log('Error in verifyToken middleware:', e);
return res.status(500).send('Server error');
}
};
GenerateToken.js
export const generateToken = (user) => {
try {
return jwt.sign({ id: user.id }, process.env.SECRET_KEY, { expiresIn: '30m' });
} catch (e) {
console.log('Error generating token:', e);
}
};
const router = express.Router();
routes.get('/' , startpage)
router.post('/register', register);
router.post('/login', login);
router.get('/home', verifyToken, homepage);
router.get('/buynow', verifyToken, buynow);
Here , / -> Startpage has two forms
Login form , register form
Loginform -> post method and /login action
Registerform -> post method and /register action
I use generateToken function on /login and it gives token./home -> will renders a home ejs file
I use generateToken () function in /login route
Like : let token= generateToken(userVar)
Token is generated correctly
It gives the token and but I can’t verify it , it responds missing token , but it can’t get req.headers.authorization and it displays undefined