使用 axios 在标头中传递 JWT [英] Passing JWT in headers with axios

查看:64
本文介绍了使用 axios 在标头中传递 JWT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个带有节点后端的小项目,并在前端做出反应以通过 REST 调用获取数据.我使用了 Axios 库,但是当我通过它传递标头时,我不断收到错误消息:

I've created a small project with a node back-end and react front-end to fetch the data through REST calls. I used Axios library, but when I pass the headers with it I keep getting an error saying:

加载资源失败:服务器响应状态为 401(未授权).

我发现了两种方法,但都不起作用.他们是:

I found out two methods and both did not work. They are:

export const getUsersDetails=()=>{
  console.log('calling');
  return (dispatch) => {
    return axios.get('http://localhost:3030/users',{headers: { "Authorization": localStorage.getItem('jwtToken') }}).then((data)=>{
                 console.log('data comming',data);
                dispatch(getUsersData(data));
            }).catch((error)=>{
              console.log('error comming',error);
                dispatch(errorgetUsersData(error));
            });
        };
}

axios.defaults.headers.common['Authorization'] = localStorage.getItem('jwtToken');

但是当我使用邮递员时,我会从后端获取所需的数据.我不断收到此未经授权的错误的任何特殊原因?.

But When I use postman I am getting the required data from the backend. Any particular reason why I keep getting this Unauthorized error?.

推荐答案

需要在token前连接'Bearer',像这样:

You need to concatenate 'Bearer ' before the token, like this:

axios.defaults.headers.common['Authorization'] = 
                                'Bearer ' + localStorage.getItem('jwtToken');

这篇关于使用 axios 在标头中传递 JWT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆