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://example.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
Yea, for clarity:
let config = {baseURL: 'https://some-domain.example/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.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-
urlencoded';
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.example/api/'
});
const customAxios = axios.create({
baseURL: 'https://some-custom-domain.example/api/'
});
export {
mainAxios,
customAxios
};