使用 JWT 的身份验证通过 GET 请求返回空数组 [NodeJS]
Authenication with JWT returning empty array with a GET request [NodeJS]
尝试使用 NodeJS 练习 JWT,但是当我尝试 运行 使用授权的 headers 的 GET 请求时:Bearer,它 returns 一个数组而不是 object 使用令牌,我尝试使用 Postman 应用程序但无济于事
这是代码,获取和post请求代码:
const express = require('express');
require('dotenv').config();
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const app = express();
const user = [
{
username: 'John',
email: 'john@gmail.com'
},
{
username: "Joshua",
email: 'joshua@gmail.com'
}
]
app.use(express.json())
app.get('/api', authenicateToken, (req, res,) => {
res.json(user.filter(post => post.username === req.body.name))
})
app.post('/login', (req, res) => {
const username = req.body.username
const use = { name: username }
const accessToken = jwt.sign(use, process.env.ACCESS_KEY)
res.json({ accessToken: accessToken })
})
function authenicateToken (req, res, next) {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if(token === null) return res.sendStatus(403)
jwt.verify(token, process.env.ACCESS_KEY, (err, user) => {
if(err) return res.sendStatus(403)
req.user = user
next()
})
}
app.listen(4000, () => {
console.log('Can you hear me?');
})
filter
returns一个数组,用find
方法returns单项
res.json(user.find(post => post.username === req.body.name))
尝试使用 NodeJS 练习 JWT,但是当我尝试 运行 使用授权的 headers 的 GET 请求时:Bearer,它 returns 一个数组而不是 object 使用令牌,我尝试使用 Postman 应用程序但无济于事
这是代码,获取和post请求代码:
const express = require('express');
require('dotenv').config();
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const app = express();
const user = [
{
username: 'John',
email: 'john@gmail.com'
},
{
username: "Joshua",
email: 'joshua@gmail.com'
}
]
app.use(express.json())
app.get('/api', authenicateToken, (req, res,) => {
res.json(user.filter(post => post.username === req.body.name))
})
app.post('/login', (req, res) => {
const username = req.body.username
const use = { name: username }
const accessToken = jwt.sign(use, process.env.ACCESS_KEY)
res.json({ accessToken: accessToken })
})
function authenicateToken (req, res, next) {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if(token === null) return res.sendStatus(403)
jwt.verify(token, process.env.ACCESS_KEY, (err, user) => {
if(err) return res.sendStatus(403)
req.user = user
next()
})
}
app.listen(4000, () => {
console.log('Can you hear me?');
})
filter
returns一个数组,用find
方法returns单项
res.json(user.find(post => post.username === req.body.name))