简体   繁体   English

如何添加 JWT 令牌认证以保护路由

[英]How to add JWT token authentication to protect routes

I've added the required code but still I'm getting:我已经添加了所需的代码,但我仍然得到:

Cannot GET /api/login无法获取 /api/login

I'm testing this on Postman as well as directly on browser.我正在 Postman 以及直接在浏览器上对此进行测试。 However I still haven't fully implemented JWT authentication.但是我还没有完全实现 JWT 身份验证。 But other api end points like api/articles , api/update , api/delete etc are working fine.但其他 api 端点如api/articlesapi/updateapi/delete等工作正常。 Here is my code.这是我的代码。

server.js服务器.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 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 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.我也有其他路线,但我没有在这里提及,因为它们运行良好并返回正确的 json 响应。

Please point out my mistake.请指出我的错误。

Your login api is supposed to handle a POST request (as you have defined the route with router.post('/login',) ).您的登录 api 应该处理 POST 请求(因为您已经使用 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.由于您从邮递员/浏览器发出 GET 请求,因此您的请求与您定义的任何路由都不匹配。

Change the request type in the postman to POST while making the request to get a response from the server.将 postman 中的请求类型更改为 POST,同时发出请求以从服务器获取响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM