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

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


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'}});


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

import axios from "axios";    // For common configaxios.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};


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';```