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