首页 > 其他 > 详细

vue项目接口域名动态获取

时间:2019-04-13 15:41:35      阅读:2031      评论:0      收藏:0      [点我收藏+]

需求:

接口域名是从外部 .json 文件里获取的。

思路:

在开始加载项目前 进行接口域名获取,然后重置 接口域名的配置项。

实现:

1、config/index.js 文件 进行基础配置

import axios from axios

const config = {
  requestUrl: http://qiniu.eightyin.cn/path.json, //动态域名所在地址
  baseUrl: {
    dev: /api/,
    pro: http://xxx.com/ // 接口域名,会被动态覆盖
  },

  requestRemoteIp: () => { // 动态获取
    return new Promise((resolve, reject) => {
      axios.get(config.requestUrl).then(response =>
      {
    
        config.baseUrl.pro = response.data.data.path;
        config.img.domain = config.baseUrl.pro;
        resolve()
      }, err => {
        reject()
      });
    });
  }
}

export default config

2、项目下main.js 文件 进行动态获取

import config from @/config/index.js

// 读取接口域名
config.requestRemoteIp().then(res => {
  /* eslint-disable no-new */
  new Vue({
    el: #app,
 
    router,
    components: { App },
    template: <App/>
  })
}, () => {
  /* eslint-disable no-new */
  new Vue({
    el: #app,
    
    router,
    components: { App },
    template: <App/>
  })
});

3、请求数据

const instance = axios.create({
      baseURL: process.env.NODE_ENV === development ? config.baseUrl.dev : config.baseUrl.pro
    })

 

vue项目接口域名动态获取

原文:https://www.cnblogs.com/fan-zha/p/10701129.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!