Attach Authorization header for all axios requests

前端 未结 9 1989
灰色年华
灰色年华 2020-12-04 05:17

I have a react/redux application that fetches a token from an api server. After the user authenticates I\'d like to make all axios requests have that token as an Authorizati

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 05:37

    If you use "axios": "^0.17.1" version you can do like this:

    Create instance of axios:

    // Default config options
      const defaultOptions = {
        baseURL: ,
        headers: {
          'Content-Type': 'application/json',
        },
      };
    
      // Create instance
      let instance = axios.create(defaultOptions);
    
      // Set the AUTH token for any request
      instance.interceptors.request.use(function (config) {
        const token = localStorage.getItem('token');
        config.headers.Authorization =  token ? `Bearer ${token}` : '';
        return config;
      });
    

    Then for any request the token will be select from localStorage and will be added to the request headers.

    I'm using the same instance all over the app with this code:

    import axios from 'axios';
    
    const fetchClient = () => {
      const defaultOptions = {
        baseURL: process.env.REACT_APP_API_PATH,
        method: 'get',
        headers: {
          'Content-Type': 'application/json',
        },
      };
    
      // Create instance
      let instance = axios.create(defaultOptions);
    
      // Set the AUTH token for any request
      instance.interceptors.request.use(function (config) {
        const token = localStorage.getItem('token');
        config.headers.Authorization =  token ? `Bearer ${token}` : '';
        return config;
      });
    
      return instance;
    };
    
    export default fetchClient();
    

    Good luck.

提交回复
热议问题