Sending the bearer token with axios

前端 未结 9 1312
野趣味
野趣味 2020-11-28 21:21

In my react app i am using axios to perform the REST api requests.

But it\'s unable to send the Authorization header with the request.

Here is my co

相关标签:
9条回答
  • 2020-11-28 22:08

    You can create config once and use it everywhere.

    const instance = axios.create({
      baseURL: 'https://some-domain.com/api/',
      timeout: 1000,
      headers: {'Authorization': 'Bearer '+token}
    });
    
    instance.get('/path')
    .then(response => {
        return response.data;
    })
    
    0 讨论(0)
  • 2020-11-28 22:08

    This is what i also faced. The token which u are passing is not correct.

    Just Hardcode the token and pass, you will get the correct response. But if token is not passed in single quote '', then it will surely fail. It must be in format 'Authorization': 'Bearer YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ', where after Bearer one space must be present, also inside single quotes, this is very important.

    var token = "YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ";
    
    var headers = {
      Authorization: "Bearer " + token,
      Accept: "application/json, text/plain, */*",
      "Content-Type": "application/json"
    };
    

    IMP: The above code will work But if u post something like:

    'Authorization': 'Bearer '+ YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ, it will fail

    or-----the below code also will fail, i hope u understand the basic difference

    var token = YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjA0YmEzZmZjN2I1MmI4MDJkNQ;
    
    var headers = {
      Authorization: "Bearer " + token,
      Accept: "application/json, text/plain, */*",
      "Content-Type": "application/json"
    };
    
    0 讨论(0)
  • 2020-11-28 22:11

    This works and I need to set the token only once in my app.js:

    axios.defaults.headers.common = {
        'Authorization': 'Bearer ' + token
    };
    

    Then I can make requests in my components without setting the header again.

    "axios": "^0.19.0",

    0 讨论(0)
提交回复
热议问题