vue-element-admin 打包生成外部配置文件修改后端访问地址

一般,我们前端打包项目之前要先问上级要一个线上环境的访问ip,这样才能确保访问得到。但是,这种方式一般很笨戳,每次都要问,直到我的上级被我问烦了...

上级:"你打包的时候能不能生成一个配置文件,里面包含了访问的ip地址,打包好后也可以进行修改,无需再进行打包"

我:“。。。。。。。。”

上级:“我知道你可以的,加油,下一个版本要实现这个功能”

我:“,,,,,,,,,”

 

于是我开始百度,因为我做的一般是内部管理系统,使用的框架网上现成的框架,vue-element-admin-master,这个框架方便简单功能多,简直是好用到不得了。

至于实现打包生成配置文件那个东西实现起来也比较简单,找到public文件,然后在这个文件夹下面创建一个config.js,如下

 

 

 然后编辑config.js

var PLATFROM_CONFIG = {};
PLATFROM_CONFIG.baseUrl = "请在这里输入访问地址"

 

 

 找到你封装好的axios文件,我的是这样

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import qs from 'qs';
// create an axios instance
let baseURL = window.PLATFROM_CONFIG.baseUrl
const service = axios.create({
  baseURL:baseURL 
, // url = base url + request url // withCredentials: true, // send cookies when cross-domain requests timeout: 5000 // request timeout }) // request interceptor service.interceptors.request.use( config => { // do something before request is sent if (store.getters.token) { // let each request carry token // ['X-Token'] is a custom headers key // please modify it according to the actual situation config.headers['X-Token'] = getToken() } return config }, error => { // do something with request error console.log(error) // for debug return Promise.reject(error) } ) // response interceptor service.interceptors.response.use( /** * If you want to get http information such as headers or status * Please return response => response */ /** * Determine the request status by custom code * Here is just an example * You can also judge the status by HTTP Status Code */ response => { const res = response.data // if the custom code is not 20000, it is judged as an error. if (res.code !== 20000) { Message({ message: res.message || 'Error', type: 'error', duration: 5 * 1000 }) // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired; if (res.code === 50008 || res.code === 50012 || res.code === 50014) { // to re-login MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', { confirmButtonText: 'Re-Login', cancelButtonText: 'Cancel', type: 'warning' }).then(() => { store.dispatch('user/resetToken').then(() => { location.reload() }) }) } return Promise.reject(new Error(res.message || 'Error')) } else { return res } }, error => { console.log('err' + error) // for debug Message({ message: error.message, type: 'error', duration: 5 * 1000 }) return Promise.reject(error) } ) export default service

  修改的只有标红的两行,修改好这些,再引入config.js,

 

 

      运行打包后,你的项目就同这个样式,

 

 打开config.js,你会发现,修改baseUrl就可以了。

方法虽然笨戳,但是实现就可以啦,还有,这个方法是针对框架 vue-element-admin 的,如果应用在其他项目上,基本原理是 一样的,但是config.js文件创建的位置不一样,我有一个项目就是写在static下面的,所以请根据自己的项目情况创建config.js

posted @ 2020-03-31 10:45  秃头代码侠  阅读(8643)  评论(0编辑  收藏  举报