【问题标题】:Having trouble with JsonWebToken; JsonWebToken Error: JWT must be providedJsonWebToken 遇到问题; JsonWebToken 错误:必须提供 JWT
【发布时间】:2018-07-06 16:39:55
【问题描述】:

我正在使用 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 });
}
});

【问题讨论】:

  • 返回什么:const token = req.body.jwt; IE,console.log(token) 给出了什么?
  • 应该是收到的JWT token。后者将显示它收到的令牌。

标签: javascript node.js express login jwt


【解决方案1】:

必须提供jwt

当即将到来的令牌为空或为空时会发生此错误。

【讨论】:

  • 它为空或为空的常见原因是什么?
  • @Esqarrouth,当客户出于任何原因没有发送它时。
  • 来晚了,但是对我来说,出现了这个错误,因为令牌丢失了,这是因为用户未经身份验证
【解决方案2】:

可能是您没有在特定文件中定义jwt,或者它为空或空。因此你得到一个错误。我只是测试你的代码,它对我有用。可能是您没有将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,并且无法保证它何时会运行。

【讨论】:

  • 我设法解决了它:我将请求发送为“jwt”:“token”。当我发送 jwt:"token" 时,它工作正常。感谢您的宝贵时间。
猜你喜欢
  • 2016-03-13
  • 2016-01-21
  • 2020-11-26
  • 2022-01-09
  • 2019-04-23
  • 2016-01-10
  • 1970-01-01
  • 2019-01-16
  • 2016-11-27
相关资源
最近更新 更多