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

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

问题描述

我创建了一个带有节点后端的小项目,并通过使用 Axios 库的REST调用来反馈前端来获取数据。但是当我用它传递标题时,我不断收到错误说 无法加载资源:服务器响应状态为401(未授权) 。我发现了两种方法,但都没有用。

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 Failed to load resource: the server responded with a status of 401 (Unauthorized). I found out two methods and both did not work.

它们是

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 im getting the required data from the backend. Any particular reason why im keep getting this Unauthorized error?.

推荐答案

您需要在令牌之前连接'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天全站免登陆