Sending the bearer token with axios

前端 未结 9 1311
野趣味
野趣味 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 21:52
    const config = {
        headers: { Authorization: `Bearer ${token}` }
    };
    
    const bodyParameters = {
       key: "value"
    };
    
    Axios.post( 
      'http://localhost:8000/api/v1/get_token_payloads',
      bodyParameters,
      config
    ).then(console.log).catch(console.log);
    

    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.

    0 讨论(0)
  • 2020-11-28 21:56

    By using Axios interceptor:

    const service = axios.create({
      timeout: 20000 // request timeout
    });
    
    // request interceptor
    
    service.interceptors.request.use(
      config => {
        // Do something before request is sent
    
        config.headers["Authorization"] = "bearer " + getToken();
        return config;
      },
      error => {
        Promise.reject(error);
      }
    );
    
    0 讨论(0)
  • 2020-11-28 22: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)
    });
    
    0 讨论(0)
  • 2020-11-28 22:05

    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

    0 讨论(0)
  • 2020-11-28 22:05

    axios by itself comes with two useful "methods" the interceptors that are none but middlewares between the request and the response. so if on each request you want to send the token. Use the interceptor.request.

    I made apackage that helps you out:

    $ npm i axios-es6-class
    

    Now you can use axios as class

    export class UserApi extends Api {
        constructor (config) {
            super(config);
    
            // this middleware is been called right before the http request is made.
            this.interceptors.request.use(param => {
                return {
                    ...param,
                    defaults: {
                        headers: {
                            ...param.headers,
                            "Authorization": `Bearer ${this.getToken()}`
                        },
                    }
                }
            });
    
          this.login = this.login.bind(this);
          this.getSome = this.getSome.bind(this);
       }
    
       login (credentials) {
          return this.post("/end-point", {...credentials})
          .then(response => this.setToken(response.data))
          .catch(this.error);
       }
    
    
       getSome () {
          return this.get("/end-point")
          .then(this.success)
          .catch(this.error);
       }
    }
    

    I mean the implementation of the middleware depends on you, or if you prefer to create your own axios-es6-class https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a it is the medium post where it came from

    0 讨论(0)
  • 2020-11-28 22:08

    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:

    import axios from 'axios';
    axios.defaults.baseURL = 'http://localhost:1010/'
    axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
    export default axios;
    

    Edit, Thanks to Jason Norwood-Young.

    Some API require bearer to be written as Bearer, so you can do:

    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.

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