manu manu - 11 months ago 196
Javascript Question

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

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 I'm using Axios. I know I got it to work pretty well at some point, but today when starting my project, it's just impossible to get both apis to work simultaneously.

Here is my login service:

import axiosTrainingAPI from 'axios'

axiosTrainingAPI.defaults.baseURL = 'https://api.**********.com'

const trainingAPI = {
login (credentials) {
return new Promise((resolve, reject) => {
axiosTrainingAPI.post('/services/auth.php', credentials)
.then(response => {
resolve(response.data)
}).catch(response => {
reject(response.status)
})
})
}
}

export default trainingAPI


Here is my news service:

import axiosGoogleNewsAPI from 'axios'

axiosGoogleNewsAPI.defaults.baseURL = 'https://newsapi.org'

const googleNewsAPI = {
getPosts (newsId) {
return new Promise((resolve, reject) => {
axiosGoogleNewsAPI.get(`/v2/everything?q=${newsId}&sortBy=publishedAt&apiKey=***********`)
.then(response => {
resolve(response.data)
}).catch(response => {
reject(response.status)
})
})
}
}

export default googleNewsAPI


Both those services are in different JS files and are imported in different vue files but it seems that now they cannot coexist and there is always one overwriting the baseURL of the other (not always the same) almost like if the Axios instance was the same in both cases. So some time the first service uses the second one's baseURL, sometimes it's the second that uses the first one's baseURL...

I don't know exactly the scope of 'import' because it's pretty new to me but both instances are in different files, have different names so I don't really understand how they get mixed up. Except if 'import' always calls the same instance of a module but then how do I work with 2 apis? And why did it work yesterday... I'm confused.

Answer Source

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'}
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download