VUE2.0项目实现动态修改请求的服务器地址

最近需求: 要求可以动态修改请求baseURL。

1、安装插件 npm install --save-dev generate-asset-webpack-plugin

2、修改 vue.config.js

module.exports = {
  configureWebpack:{
const GenerateAssetPlugin = require('generate-asset-webpack-plugin');
const cfgJson = require('./serverconfig.json') //这里引入的地址就是后面新建serverconfig.json的地址
var createServerConfig = function (compilation) {
  return JSON.stringify(cfgJson);
}

chainWebpack(config){
      config
      .plugin('GenerateAssetPlugin')
      .use('generate-asset-webpack-plugin', [{
        filename: 'serverconfig.json',
        fn: (compilation, cb) => {
          cb(null, createServerConfig(compilation));
        },
        extraFiles: []
      }])
}
    }
}

3、在main.js


Vue.prototype.getConfigJson = function () {
  axios.get("serverconfig.json").then((result) => {
    localStorage.setItem('ApiUrl',result.data.VUE_APP_SERVE_URL);
  }).catch((error) => {
    console.log('getConfigJson Error!', error)
  })
}

4、在app.vue

  mounted () {
    this.getConfigJson();
  },

5、修改Axios的BaseURL地址。

const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, 
  baseURL:  process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API : localStorage.getItem('ApiUrl'),
  timeout: 5000, // request timeout
  headers: { language: getLocalLang() }
  // headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}// qs序列号需要携带头部
})

7、 新建JSON文件serverconfig.json ,不然打包后报错

{"VUE_APP_SERVE_URL":"http://210.132.158.3:1000/api"}

7、在每次 npm run build 打包的时候, 修改dist文件夹中的 serverconfig.json 中的地址即可

一些小玩意

https://www.jianshu.com/p/3f0b7ea9df53

posted @ 2021-09-29 09:20  云霄紫潭  阅读(1227)  评论(0编辑  收藏  举报