【问题标题】:VueJS and Axios multiple base URLs for prod envVueJS 和 Axios 用于 prod env 的多个基本 URL
【发布时间】:2018-10-08 06:57:50
【问题描述】:

要在 prod 和 dev 环境中配置我的应用程序,我目前使用类似:

let baseURL;

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
  baseURL = 'http://127.0.0.1/';
} else {
  baseURL = 'http://api.example.com';
}

export const HTTP = axios.create(
  {
    baseURL: baseURL,
    headers: {...}
  })

然后我用

查询API
HTTP.get(...).then(...)

现在我需要使用不同的基本 URL 连接到多个端点。

例如,我需要这样做:

HTTP.userApi.get()
HTTP.productApi.get()

如何使用多个端点配置生产/开发环境?

【问题讨论】:

    标签: vue.js axios


    【解决方案1】:

    axios方面有两种选择:

    1. 为自定义请求创建custom instance
    // Create an instance using the config defaults provided by the library
    // At this point the timeout config value is `0` as is the default for the library
    const instance = axios.create();
    
    // set a default baseURL for this particular instance
    instance.defaults.baseURL= 'http://new-root.com';
    
    1. 使用 request config 对每个请求使用自定义 baseURL
    axios.get('my/url', { baseURL: 'http://new-root.com' })
    

    谈到您的情况,我将为每个“端点”创建一个 axios 实例 - HTTP.userApi 将是实例,HTTP.productApi 将是另一个实例。如果您愿意,他们总是可以分享共同的东西;)

    祝你好运!

    【讨论】:

    • 我接受了答案,但是如何使用 export const HTTP = axios.create() 创建实例 HTTP.xxxApi ?
    • 使用版本 1 中的完整示例,然后导出 instance
    猜你喜欢
    • 2021-08-19
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 2018-05-04
    • 2018-04-29
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    相关资源
    最近更新 更多