/**
* axios配置
*/
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import store from '@/store'
import router from '@/router'
import setting from './setting'
import {MessageBox} from 'element-ui'
Vue.use(VueAxios, axios);
axios.defaults.baseURL = setting.baseURL;
axios.defaults.headers.common[setting.tokenHeaderName] = store.state.user.token;
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
//根据vuex store内容动态设置baseurl
//console.log("config:"+JSON.stringify(config));
//console.log("location:"+window.location.host); //document.location;
if(window.location.host.indexOf('192.168.99')>-1 || window.location.host.indexOf('localhost')>-1){
//判断是内网地址的话,就请求内网后端接口地址
config.baseURL = setting.baseURL;
}else{
//判断是外网地址的话,就请求外网后端接口地址
config.baseURL = setting.baseWWWURL;
}
console.log("config baseURL:"+config.baseURL);
return config
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error)
});
/* 响应拦截器 */
axios.interceptors.response.use((res) => {
if (res.data.code === 401) { // 登录过期处理
if (res.config.url === setting.menuUrl) {
store.dispatch('user/setToken').then(() => {
location.replace('/');
});
return;
}
MessageBox.alert('登录状态已过期,请退出重新登录!', '系统提示', {
confirmButtonText: '重新登录',
callback: action => {
if (action === 'confirm') {
store.dispatch('user/setToken').then(() => {
router.push({path: '/login'});
});
}
},
beforeClose: () => {
MessageBox.close();
}
});
return Promise.reject(new Error(res.data.msg));
}
// token自动续期
let access_token = res.headers[setting.tokenHeaderName];
if (access_token) store.dispatch('user/setToken', access_token);
return res;
}, (error) => {
return Promise.reject(error);
});
Vue Axios 根据地址判断是局域网还是外网访问配置不同地址
最新推荐文章于 2024-05-21 20:04:34 发布