如何在同一应用程序中使用具有不同 baseURL 的 2 个 Axios 实例 (vue.js)

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

我正在努力学习 vue.js 所以我制作了一个小应用程序,它显示来自 API 的新闻文章,并在另一个视图中允许用户登录到另一个服务器。

为此,我使用的是 Axios。我知道我在某些时候让它工作得很好,但今天开始我的项目时,让两个 api 同时工作是不可能的。

这是我的登录服务:

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

这是我的新闻服务:

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

这两个服务都在不同的 JS 文件中,并在不同的 vue 文件中导入,但现在它们似乎不能共存,并且总是有一个覆盖另一个的 baseURL(不总是相同的)几乎就像 Axios两种情况下的实例都相同。所以有时第一个服务使用第二个的 baseURL,有时是第二个使用第一个的 baseURL...

我不知道 'import' 的确切范围,因为它对我来说很新,但两个实例都在不同的文件中,具有不同的名称,所以我真的不明白它们是如何混淆的。除非 'import' 总是调用模块的同一个实例,但是我该如何使用 2 个 api?还有为什么昨天能用...我很困惑。

您需要 create a new instance of axios 为每个 API 具有不同 baseURL.

的自定义配置
var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

是的,为清楚起见:

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

此外,您可以指定将应用于每个请求的配置默认值。

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

您可以简单地使用多个 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
};

我有同样的问题,为了解决它,我创建了一个接口和一个函数(TS 中的示例):

export function createClient(baseURL: string) {
  return axios.create({
    baseURL: baseURL,
    headers: { "Content-Type": "application/json" }
  });
}

export interface ConfigurableApi {
  configure(config: Configuration);
}

我为每个客户创建了一个 class

@Singleton()
export class ApiOfClientA implements ConfigurableApi {
  client!: AxiosInstance;

  configure(config: Configuration) {
    this.client = createClient(config.baseURL);
  }

  ...
}

如果你想使用 JS,你可以这样做:

import axios from "axios";

let clientA;
const ClientA = {
    init(baseURL) {
        clientA = axios.create({
            baseURL: `${baseURL}`,
            headers: {"Content-Type": "application/json"}
        });
    },
    ...
};

export {ClientA}; 

然后将其导入到您需要使用的文件中即可:

import {ClientA} from "./api/client-a";