我已经查看了这个堆栈溢出条目Node.js - Express.js JWT 总是在浏览器响应中返回一个无效的令牌错误,但我在那里找不到解决方案。
我试图编写一个小型节点应用程序作为使用 JWT 访问令牌的概念证明。我去了http://jwt.io/并尝试跟随视频教程。我已经生成了一个令牌,但是在实际使用该令牌时,我得到一个“UnauthorizedError:无效签名”错误。下面是我的源代码
const myUsername = 'ironflag';
const express = require('express');
const expressJWT = require('express-jwt');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const PORT = 2000;
// App
const app = express();
//fake data
let killerBeez = {
members: 9,
location: 'staten island',
stateOfBeing: 'wu-tang forever',
memberList: [
{
name: 'RZA',
alias: ['Bobby Steels', 'Prince Raheem', 'Bobby Digital', 'The Abbot']
},
{
name: 'GZA',
alias: ['The Genius','Drunken Monk']
},
{
name: 'Ol\' Dirty Bastard',
alias: ['Big Baby Jesus', 'Dirt McGirt', 'Ason Unique']
},
{
name: 'Inspecta Deck',
alias: 'Rebel INS'
},
{
name: 'Raekwon the Chef',
alias: 'Lex Diamond'
},
{
name: 'U-God',
alias: 'Baby U'
},
{
name: 'Ghostface Killah',
alias: ['Tony Starks', 'Big Ghost', 'Ironman']
},
{
name: 'Method Man',
alias: ['Johnny Blaze', 'Iron Lung']
},
{
name: 'Capadonna'
}
]
};
app.use(bodyParser.urlencoded());
app.use(expressJWT({ secret: 'wutangclan' }).unless({ path: ['/', '/login', '/wutangclan'] }));
app.get('/', function (req, res) {
res.send('Hello world\n');
});
app.get('/wutangclan', function (req, res) {
res.send(killerBeez);
});
app.post('/login', function (req, res) {
if(!req.body.username || myUsername !== req.body.username) {
res.status(400).send('username required');
return;
}
let myToken = jwt.sign({username: req.body.username}, '36 chambers');
res.status(200).json({token: myToken});
});
app.post('/shaolin ', function (req, res) {
if(req.body.location) {
killerBeez.location = req.body.location;
res.status(200).send('location updated');
} else {
res.status(400).send('location required');
}
});
app.listen(PORT, function () {
console.log(`Example app listening on port ${PORT}!`);
});