簡體   English   中英

JsonWebToken 遇到問題; JsonWebToken 錯誤:必須提供 JWT

[英]Having trouble with JsonWebToken; JsonWebToken Error: JWT must be provided

我正在使用 Vue 構建我的第一個 SPA 項目。

我決定使用 NodeJS 作為后端,但是,我很頭疼使用 JsonWebToken 構建登錄功能。

我寫了一些代碼來看看 JWT 是如何工作的,當我試圖查看 JWT 是如何被驗證的時,服務器給了我一個錯誤。

JsonWebTokenError: jwt must be provided
at Object.module.exports [as verify] (c:\dir\node_modules\jsonwebtoken\verify.js:39:17)
at c:\projects\practice\demo\back\server.js:34:17

下面是我的 server.js 的代碼

這是導入東西的代碼。

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

api.use(bodyParser.json());
api.use(bodyParser.urlencoded({ extended: true }));

這是用於發布 JWT 的 API。

api.post('/secure', function (req, res) {
const token = jwt.sign({ user: {id:1, name:'ME!', role: 'average'} }, 'dsfklgj');
console.log(token);
res.json({jwt: token});
});

這是用於檢查 JWT 的 API。

api.post('/check/post', function (req, res) {
const token = req.body.jwt;
const x = jwt.verify(token, 'dsfklgj', function (err, decoded) {
if (err) throw err;
console.log(decoded);
});
if (x != true) {
res.json({ auth: false });
}else {
res.json({ auth: true });
}
});

必須提供 jwt

當即將到來的令牌為空或為空時,會發生此錯誤。

可能是您沒有在特定文件中定義jwt ,或者它為 null 或空。 因此你得到一個錯誤。 我只是測試你的代碼,它對我有用。 可能是您沒有正確地將jwt令牌發送到 post 請求中。

const express = require('express');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const http = require('http');
const api = express();

api.use(bodyParser.json());
api.use(bodyParser.urlencoded({ extended: true }));

api.post('/secure', function(req, res) {
    const token = jwt.sign({ user: { id: 1, name: 'ME!', role: 'average' } }, 'dsfklgj');
    console.log(token);
    res.json({ jwt: token });
});


api.post('/check/post', function(req, res) {
    const token = req.body.jwt;
    console.log('token: ' + token);
    const x = jwt.verify(token, 'dsfklgj', function(err, decoded) {
        if (err) throw err;
        console.log(decoded);
    });
    console.log(x);
    if (x != true) {
        res.json({ auth: false });
    } else {
        res.json({ auth: true });
    }
});

api.set('port', 3000);
var server = http.createServer(api);
server.listen(api.get('port'), function() {
    console.log("Express server listening on port " + api.get('port'));
});

順便說一句,沒有辦法像這樣測試它const x = jwt.verify(token, 'dsfklgj', function (err, decoded) { 。要么以Sync方式編寫它,要么在async回調函數中檢查條件。在你的情況下, x將是undefined的,並且無法保證它何時運行。

無論誰閱讀本文,請確保Authorization標頭的值為Bearer <Access Token> 承載<空白>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM