Warm tip: This article is reproduced from serverfault.com, please click

How to add JWT token authentication to protect routes

发布于 2020-11-28 05:47:03

I've added the required code but still I'm getting:

Cannot GET /api/login

I'm testing this on Postman as well as directly on browser. However I still haven't fully implemented JWT authentication. But other api end points like api/articles, api/update, api/delete etc are working fine. Here is my code.

server.js

const express = require('express');
const bodyParser = require('body-parser');

const port = (process.env.PORT || 3000);
const app = express();

const api = require('./routes/api');
const cors = require('cors');

app.use(bodyParser.json());
app.use(cors());

app.use('/api', api);
app.get('/', function(req, res) {
    res.send('Server is up and running!');
})

app.listen((3000), function() {
    console.log('Server listening on PORT ' + port)
});

api.js

...
const jwt = require('jsonwebtoken');

router.post('/login', (req, res) => {
    const user = {
        id: 1,
        username: 'tanzeel',
        email: 'tanzeel@fakemail.com',
        password: 'fakepassword' 
    }

    jwt.sign({ user }, 'secretKey', (err, token) => {
        res.json({
            token
        })
    })
})

package.json

...
"dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.6.13",
    "serve": "^11.3.2"
}

I've other routes as well but I'm not mentioning here as they are working perfectly and returning the right json response.

Please point out my mistake.

Questioner
Tanzeel
Viewed
11
Naveen Chahar 2020-11-28 15:09:33

Your login api is supposed to handle a POST request (as you have defined the route with router.post('/login',) ). Since you are making a GET request from the postman/browser, your request doesn't match with any of the routes defined by you.

Change the request type in the postman to POST while making the request to get a response from the server.