Sending the bearer token with axios

2019-01-22 18:30发布

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 code:

tokenPayload() {
  let config = {
    headers: {
      'Authorization': 'Bearer ' + validToken()
    }
  }
  Axios.post( 
      'http://localhost:8000/api/v1/get_token_payloads',
      config
    )
    .then( ( response ) => {
      console.log( response )
    } )
    .catch()
}

Here the validToken() method would simply return the token from browser storage.

All requests are having a 500 error response saying that

The token could not be parsed from the request

from the back-end.

How to send the authorization header with each requests? Would you recommend any other module with react?

5条回答
Bombasti
2楼-- · 2019-01-22 19:02

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;
})
查看更多
相关推荐>>
3楼-- · 2019-01-22 19:02

If you want to some data after passing token in header so that try this code

const api = 'your api'; 
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
  console.log(error)
});
查看更多
【Aperson】
4楼-- · 2019-01-22 19:05
var config = {
    headers: {'Authorization': "bearer " + token}
};

var bodyParameters = {
   key: "value"
}

Axios.post( 
  'http://localhost:8000/api/v1/get_token_payloads',
  bodyParameters,
  config
).then((response) => {
  console.log(response)
}).catch((error) => {
  console.log(error)
});

The first parameter is the URL.
The second is the JSON body that will be sent along your request.
The third parameter are the headers (among other things). Which is JSON as well.

查看更多
Rolldiameter
5楼-- · 2019-01-22 19:17

Here is a unique way of setting Authorization token in axios. Setting configuration to every axios call is not a good idea and you can change the default Authorization token by:

const axios = require('axios');
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}

Now you don't need to set configuration to every API call. Now Authorization token is set to every axios call.

查看更多
The star\"
6楼-- · 2019-01-22 19:28

The second parameter of axios.post is data (not config). config is the third parameter. Please see this for details: https://github.com/mzabriskie/axios#axiosposturl-data-config

查看更多
登录 后发表回答