一般,我們前端打包項目之前要先問上級要一個線上環境的訪問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