我基本上是在发送带有两个标头的JSON数据。当我通过chrome开发工具查看标题详细信息时,它显示标题已发送。但是它在控制台中捕获了错误,提示未授权的401错误代码。
用户登录后,我将检索到的令牌值分配给本地存储。在本地存储中,还可以看到已检索和存储的值。 由于我是使用MERN堆栈技术开发此应用程序的,因此我在index.js文件中设置了以下默认标头值,
let token=localStorage.getItem('token');
if(token){
axios.defaults.headers.common['Content-Type']='application/x-www-form-urlencoded';
let auth_head='JWT '+localStorage.getItem('token');
axios.defaults.headers.common['Authorization']=auth_head;
console.log(auth_head);
}
出现错误后,我查看chrome开发的“网络”标签。在其中插入的书(数据)以红色高亮显示。因此,我单击它并查看它的标题值。
Request URL: http://localhost:4000/book/
Request Method: POST
Status Code: 401 Unauthorized
Remote Address: [::1]:4000
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 33
Content-Type: application/json; charset=utf-8
Date: Sun, 28 Apr 2019 10:02:53 GMT
ETag: W/"21-wNNi+vjO8gt//ITmWfqLf4aE+Ic"
X-Powered-By: Express
Provisional headers are shown
Accept: application/json, text/plain,
Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJzYXNoaWtzdSIsImlhdCI6MTU1NjQ0NTczMiwiZXhwIjoxNTU2NTMyMTMyfQ.3r2rQNA10bvFOEvI9vyED14rwFHg9oA633cvm4hp7x8
Content-Type: application/json;charset=UTF-8
Origin: http://localhost:3000
Referer: http://localhost:3000/insert_book
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
通过查看还可以确认我的令牌随附数据。但它说未经授权。顺便说一句,在我的用户控制器中,授权方法如下:
export const authorization = (req, res, next) => {
if (req.user) {
next();
} else {
return res.status(401).json({ message: 'Unauthorized User !' })
}
};
在server.js文件中,我像这样设置JWT设置
//JWT setup
app.use((req, res, next) => {
if (req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'JWT') {
jsonwebtoken.verify(req.headers.authorization.split(''), [1], 'RESTFULAPIs', (err, decode) => {
if (err) req.user = undefined;
req.user = decode;
//console.log(req.user );
//console.log(decode);
next();
});
} else {
req.user = undefined;
next();
}
});
我不知道代码中的错误在哪里。请帮助我。