【问题标题】:How to use 2 instances of Axios with different baseURL in the same app (vue.js)如何在同一个应用程序中使用 2 个具有不同 baseURL 的 Axios 实例(vue.js)
【发布时间】:2018-05-08 17:22:17
【问题描述】:

我正在尝试学习 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...

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

【问题讨论】:

    标签: javascript ecmascript-6 vue.js axios


    【解决方案1】:

    您需要为每个具有不同 baseURL 的 API 使用自定义配置 create a new instance of axios

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

    【讨论】:

    • 对了,我们可以对不同的Axios实例应用不同的拦截器集吗?
    • vue.config.js 还需要代理吗?
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      是的,为了清楚起见:

      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.headers.common['Authorization'] = AUTH_TOKEN;
      axios.defaults.headers.post['Content-Type'] = 'application/x-www-form- 
      urlencoded';```
      

      【讨论】:

        【解决方案4】:

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

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

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

        @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";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-01-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-10
          相关资源
          最近更新 更多