javascript 如何在同一个应用程序中使用具有不同 baseURL 的 2 个 Axios 实例 (vue.js)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47477594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use 2 instances of Axios with different baseURL in the same app (vue.js)
提问by manu
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.
我正在尝试学习 vue.js,所以我制作了一个小应用程序,它显示来自 API 的新闻文章,并在另一个视图中允许用户登录到另一个服务器。
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.
为此,我正在使用 Axios。我知道我在某个时候让它工作得很好,但是今天开始我的项目时,让两个 api 同时工作是不可能的。
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...
这两个服务都在不同的 JS 文件中,并导入到不同的 vue 文件中,但现在它们似乎不能共存,并且总是有一个覆盖另一个的 baseURL(并不总是相同)几乎就像 Axios 实例在两种情况。因此,有时第一个服务使用第二个服务的 baseURL,有时第二个服务使用第一个服务的 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.
我不知道“导入”的确切范围,因为它对我来说很新,但是两个实例都在不同的文件中,具有不同的名称,所以我真的不明白它们是如何混淆的。除非“导入”总是调用模块的同一个实例,但是我如何使用 2 个 api?为什么它昨天有效......我很困惑。
回答by PatrickSteele
You'll want to create a new instance of axioswith a custom config for each API you want that has a distinct baseURL.
你要创造爱可信的新实例与您希望有一个明显的每个API的自定义配置baseURL。
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
回答by Saahil Madaan
You can simply use multiple instances of axios with each having its own configuration. For example,
您可以简单地使用多个 axios 实例,每个实例都有自己的配置。例如,
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
};
回答by w3bh4ck
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';```
回答by Daniel Shterenberg
I had the same question and to solve it, I created an interface and a function (Example in TS):
我有同样的问题并要解决它,我创建了一个接口和一个函数(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:
如果您想使用 JS,您可能可以执行以下操作:
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";

