I'm trying to use a JWT token to authorize the user before allowing them to GET a "welcome" page.
Here's the code for the endpoint;
var apiRoutes = express.Router();
apiRoutes.use(bodyParser.urlencoded({ extended: true }));
apiRoutes.use(bodyParser.json());
apiRoutes.use(verifyToken);
apiRoutes.get('/', welcome)
Here's the verifyToken
function;
var verifyToken=function (req, res,next) {
var token = req.body.token || req.query.token || req.headers['token'];
if (token) {
jwt.verify(token, config.secret, function (err, currUser) {
if (err) {
res.send(err);
} else {
req.currUser = currUser;
next();
}
});
}
else {
res.status(401).send("Invalid Access");
}
};
module.exports=verifyToken;
And here's the welcome page;
module.exports=function(req, res) {
res.send('Welcome..!! Now you are now authenticated !');
};
But when I try to GET the endpoint in Postman I get this;
Cannot GET /
I've tried putting the token in Postman as parameters, as raw body JSON, in the headers, and as a form but still unable to get the welcome page. What am I missing?
To be sure that your middleware runs when the endpoint is called, you may put something like this: in your server.js
app.use('/api', apiRoutes);
and in your route fils
apiRoutes.get('/', verifyToken, welcome);
And remove it from the use