[英]jsonwebtoken, jwt crashing my app when invalid token is provided even though errorHandler middleware catches the error
[英]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.