背景
常规的vue项目分为本地开发环境和生产环境,在实际项目中,我们在打包之前在.env文件中进行地址配置然后进行打包(vue.config.js文件在开发环境中有效,打包后无效),但在部署过程中地址是不固定的,那么就需要进行动态配置,而不是每次都重新构建代码
第一步:在public中新建config.js文件,用来配置接口地址
?在config.js文件中写入
var ipConfig = {
baseUrl: 'http://192.168.10.52:9999'
}
第二步:在public下index.html中引入config.js文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta name="referrer" content="no-referrer">
</meta>
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<script src="./config.js"></script>
</body>
</html>
?第三步:在utils下新建axios.js文件,使用window.ipConfig (全局可用)进行调用,附赠axios封装代码
import axios from 'axios'
import {Message} from 'element-ui'
import store from '@/store'
import router from '@/router'
// 接口错误情况处理
const errorHandler = err => {
console.log(err, 'err')
if (err.response.status === 500) {
Message.error('服务器异常,请联系管理员!')
}
return Promise.reject(err)
}
const service = axios.create({
// process.env.NODE_ENV === 'development' 判断是否为开发环境,常规项目中通过.env文件进行读取
withCredentials: false, // cookie
// baseURL: 'http://192.168.10.52:9999/',
baseURL: window.ipConfig.baseUrl
// timeout: 100000
})
service.interceptors.request.use(
config => {
const token = store.getters['user/token']
if (token) {
config.headers.token = token
}
if (config.data && config.data.post) {
if (config.method === 'post') {
config.data.post = null
config.params = config.data
}
}
if (config.requestBase) {
config.baseURL = window.ipConfig.baseUrl
}
return config
},
error => {
console.log(error)
// return Promise.reject()
}
)
service.interceptors.response.use(response => {
// application/octet-stream
// 统一处理数据格式(JSON格式处理-字符串或json对象)
let resData
if (typeof response.data === 'string' && /{/.test(response.data)) {
try {
resData = JSON.parse(response.data)
} catch (e) {
resData = response.data
}
} else {
resData = response.data
}
// 如果自定义代码不是20000,则判断为错误.
if (resData.status && resData.status != 200 && resData.status !== true) {
MessageReset({
message: resData.msg || 'Error',
type: 'error',
duration: 5 * 1000
})
// 50008: 非法token; 50012: 其他客户端已登录; '505': Token 已过期;
if (resData.status === '505' || resData.status === '506') {
// to re-login
store.commit('user/SET_TOKEN', '')
setTimeout(() => {
router.replace({ path: '/login' })
}, 1000)
}
return Promise.reject(new Error(resData.message || 'Error'))
} else {
return resData
}
}, errorHandler)
export default service
|