How to use 2 instances of Axios with different baseURL in the same app (vue.js)

前端 未结 4 583
無奈伤痛
無奈伤痛 2021-01-01 15:41

I\'m trying to learn vue.js so I made a little app that displays news articles from an API and, in another view, allows the user to log into another server.

For this

相关标签:
4条回答
  • 2021-01-01 16:10

    You'll want to create a new instance of axios with a custom config for each API you want that has a distinct baseURL.

    var instance = axios.create({
      baseURL: 'https://some-domain.com/api/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'foobar'}
    });
    
    0 讨论(0)
  • 2021-01-01 16:17

    Yea, for clarity:

    let config = {baseURL: 'https://some-domain.com/api/',
      timeout: 1000,
      headers: {
       'X-Custom-Header': 'foobar',
        'Authorization' : `Bearer ${auth.token}` //where applicable
      }
    };
    let instance = axios.create(config);
    

    Also, You can specify config defaults that will be applied to every request.

    axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form- 
    urlencoded';```
    
    0 讨论(0)
  • 2021-01-01 16:23

    I had the same question and to solve it, I created an interface and a function (Example in TS):

    export function createClient(baseURL: string) {
      return axios.create({
        baseURL: baseURL,
        headers: { "Content-Type": "application/json" }
      });
    }
    
    export interface ConfigurableApi {
      configure(config: Configuration);
    }
    

    And for every client, I created a class

    @Singleton()
    export class ApiOfClientA implements ConfigurableApi {
      client!: AxiosInstance;
    
      configure(config: Configuration) {
        this.client = createClient(config.baseURL);
      }
    
      ...
    }
    

    If you want to use JS, you can probably do something like:

    import axios from "axios";
    
    let clientA;
    const ClientA = {
        init(baseURL) {
            clientA = axios.create({
                baseURL: `${baseURL}`,
                headers: {"Content-Type": "application/json"}
            });
        },
        ...
    };
    
    export {ClientA}; 
    

    and then just import it in the file you need to use it:

    import {ClientA} from "./api/client-a";
    
    0 讨论(0)
  • 2021-01-01 16:26

    You can simply use multiple instances of axios with each having its own configuration. For example,

    
        import axios from "axios";
    
        // For common config
        axios.defaults.headers.post["Content-Type"] = "application/json";
    
        const mainAxios = axios.create({
            baseURL: 'https://some-domain.com/api/'
        });
    
        const customAxios = axios.create({
            baseURL: 'https://some-custom-domain.com/api/'
        });
    
    
        export {
          mainAxios,
          customAxios
        };
    
    0 讨论(0)
提交回复
热议问题