无法读取主页上的令牌 - 授权:未定义承载

时间:2021-06-18 06:03:34

标签: reactjs authentication axios jwt postman

嗨,我正在登录表单中进行身份验证,在登录表单上输入正确的凭据后,我得到了令牌,但是当我转到我的 componentdidmount 所在的 Home 组件时, 给我的错误是我的 Authorization: Bearer undefined401 UnAuthorize

登录组件

handleSubmit = e => {
        e.preventDefault();

        const data ={
            username:this.username,
            password: this.password
        }
        
        axios.post('http://localhost:5000/api/auth',data)
         .then(res=>{
             console.log(res)
             localStorage.setItem('token',res.data.token);
         })
         .catch(err=>{
             console.log(err)
         })
    };
    

首页组件

 componentDidMount(){
        const config ={
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('token')
               
            }
        };
        
        
        axios.get('http://localhost:5000/api/user',config)
            .then(
                res=> {
                    console.log(res);
                },
                err =>{
                    console.log(err);
                }
                  
            )
    }

1 个答案:

答案 0 :(得分:0)

我看到 res 是一个对象,键 data 是令牌。所以你只需像这样更新:

localStorage.setItem('token',res.data);