【问题标题】:How to add JWT token authentication to protect routes如何添加 JWT 令牌认证以保护路由
【发布时间】:2021-03-10 19:05:54
【问题描述】:

我已经添加了所需的代码,但我仍然得到:

无法获取 /api/login

我正在 Postman 上以及直接在浏览器上进行测试。但是我还没有完全实现 JWT 身份验证。但其他 api 端点如 api/articlesapi/updateapi/delete 等工作正常。这是我的代码。

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"
}

我也有其他路线,但我没有在这里提及,因为它们运行良好并返回正确的 json 响应。

请指出我的错误。

【问题讨论】:

  • 为什么要向“POST”路由发出 GET 请求?

标签: node.js express npm jwt


【解决方案1】:

您的登录 api 应该处理一个 POST 请求(因为您已经使用 router.post('/login',) 定义了路由)。由于您是从邮递员/浏览器发出 GET 请求,因此您的请求与您定义的任何路由都不匹配。

将邮递员中的请求类型更改为POST,同时发出请求以从服务器获取响应。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 2019-11-22
    • 2021-12-06
    • 2019-12-15
    • 2020-08-21
    • 2020-09-25
    • 2014-10-18
    • 2020-04-22
    相关资源
    最近更新 更多