Reputation: 5
I try to set Token then get token from header but it always shows "undefined" when i console.log(req.headers['authorization'])
Here is some code
const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
const accessTokenSecret = 'youraccesstokensecret';
app.listen(8080, () => {
console.log('Authentication service started on port 8080');
});
I set token
app.get("/createJWT",function(req,res){
const accessToken = jwt.sign({ username: "myName"}, accessTokenSecret);
res.json({
accessToken
});
})
the middleware (I show req.headers['authorization'] is undefined)
const authenticateJWT = (req, res, next) => {
const authHeader = req.headers['authorization'];
console.log(authHeader)
if (authHeader) {
const token = authHeader.split(' ')[1];
jwt.verify(token, accessTokenSecret, (err, user) => {
if (err) {
return res.sendStatus(403);
}
req.user = user;
next();
});
} else {
res.sendStatus(401);
}
};
And finally, I access a route to test, req.headers['authorization'] does not have values.
app.get("/check",authenticateJWT,function(req, res){
res.send("ok")
})
please help me, thanks
Upvotes: 0
Views: 3854
Reputation: 838
So when you are calling the API form the frontend or say you are checking the API with postman are you setting up the header while requesting /check
? (I am not talking about your /createJWT
which creates the token and sends it as a response)
In your frontend code/postman you need to explicitly add the header authorization JWTtoken
while creating an HTTP request and after that your backend will receive it. Kindly check if this is not being done.
Upvotes: 1