vue+webpack切换环境和打包之后服务器配置

1.环境切换

 

 

 

 

 

 

API_ROOT: '"http://192.168.1.145:92"'

const rootUrl = process.env.API_ROOT

 

2.打包服务器配置

先安装generate-asset-webpack-plugin插件

npm install --save-dev generate-asset-webpack-plugin

在webpack.prod.conf.js里面配置

//让打包的时候输出可配置的文件
var GenerateAssetPlugin = require('generate-asset-webpack-plugin');
var createServerConfig = function (compilation) {
  let cfgJson = {
    ApiUrl: "http://192.168.1.145:92"
  };
  return JSON.stringify(cfgJson);
}
//让打包的时候输入可配置的文件
  new GenerateAssetPlugin({
      filename: 'serverConfig.json',
      fn: (compilation, cb) => {
        cb(null, createServerConfig(compilation));
      },
      extraFiles: []
    })

 

 

 

 

vuex存储

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
  serverConfig: ''
}

const getters = {
  serverConfig: state => {
    return state.serverConfig
  }
}
const mutations = {
  setServerConfig(state, serverConfig) {
    state.serverConfig = serverConfig
  }
}

const actions = {
  setServerConfigAsync({
    commit
  }, payload) {
    setTimeout(() => {
      commit('setServerConfig', payload)
    }, 1000)
  }
}

const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})

export default store

 

 

App.vue

<script>
import { mapMutations } from 'vuex'
import axios from 'axios'
export default {
  name: 'App',
  methods: {
    ...mapMutations({
      setServer: 'setServerConfig'
    })
  },
  mounted() {
    if (process.env.NODE_ENV === 'production') {
      console.log('生产环境')

      axios.get('serverConfig.json').then((result) => {
        this.setServer(result.data.ApiUrl)
      }).catch((error) => { console.log(error) })
    } else {
      console.log('开发环境')
    }
  }
}
</script>

 

axios配置

import axios from 'axios'
import store from '../store/index'
const rootUrl = process.env.API_ROOT

// 创建axios实例
const service = axios.create({
  timeout: 30000 // 超时时间
})

// 添加request拦截器
service.interceptors.request.use(config => {
  if (Object.keys(config.headers).length > 0) {

  }
  // console.log('headers' + config.headers)
  return config
}, error => {
  Promise.reject(error)
})

// 添加response拦截器
service.interceptors.response.use(
  response => {
    let res = {}
    res.status = response.status
    res.data = response.data
    res.headers = response.headers
    // console.log('####' + JSON.stringify(response.data))
    return res
  },
  error => {
    if (error.response && error.response.status === 404) {
      console.log('404错误')
    }
    return Promise.reject(error.response)
  }
)

// 封装get接口
// params={} 是设置默认值
export function get(url, params = {}, header = {}) {
  params.t = new Date().getTime() // get方法加一个时间参数,解决ie下可能缓存问题.
  return service({
    url: url,
    method: 'get',
    headers: header,
    params
  })
}

// 封装post请求
export function post(url, data = {}, header = {}) {
  // 默认配置
  let sendObject = {
    url: url,
    method: 'post',
    headers: header,
    data: data
  }
  sendObject.data = JSON.stringify(data)
  return service(sendObject)
}

// 封装put方法 (resfulAPI常用)
function put(url, data = {}, header = {}) {
  return service({
    url: url,
    method: 'put',
    headers: header,
    data: JSON.stringify(data)
  })
}

// 删除方法(resfulAPI常用)
function deletes(url, header = {}) {
  return service({
    url: url,
    method: 'delete',
    headers: header
  })
}

// patch方法(resfulAPI常用)
function patch(url, header = {}) {
  return service({
    url: url,
    method: 'patch',
    headers: header
  })
}

// 处理格式化URL(/demo/{id})
function render(url, data) {
  var re = /{([^]+)?}/
  var match = ''
  while ((match = re.exec(url))) {
    url = url.replace(match[0], data[match[1]])
  }
  return url
}

const fetch = (options) => {
  let url = options.url
  url = render(url, options.data)
  switch (options.method.toUpperCase()) {
    case 'GET':
      return get(url, options.data, options.header)
    case 'POST':
      return post(url, options.data, options.header)
    case 'PUT':
      return put(url, options.data, options.header)
    case 'DELETE':
      return deletes(url, options.data, options.header)
    case 'PATCH':
      return patch(url, options.data, options.header)
    default:
      return service(options)
  }
}

/**
 * 提供一个http方法
 * url 访问路径 不包括域名和项目名
 * data 参数对象
 * method 请求方式
 *  */
export function httpApiTools(url = '', body = {}, header = {}, method = 'GET') {
  var newUrl = rootUrl + url
  if (Object.keys(store.state.serverConfig).length > 0) {
    // 上线后修改配置
    console.log('store.state.serverConfig:' + store.state.serverConfig)
    newUrl = store.state.serverConfig + url
  } else {
    // 上线前多服务器环境切换
    console.log('store.state.serverConfig:' + store.state.serverConfig)
    newUrl = rootUrl + url
  }
  console.log('请求路径:' + newUrl)

  const options = {
    url: newUrl,
    data: body,
    header: header,
    method: method
  }
  return fetch(options).catch(error => {
    console.log(error)
    throw error
  })
}

/**
 * 构造url的方法
 */
export function getUrl(url = '') {
  // process.env.VUE_APP_PATH为环境变量在.env文件中配置
  return process.env.VUE_APP_PATH + url
}

 

posted @ 2020-06-18 16:07  青竹玉简  阅读(597)  评论(0编辑  收藏  举报