axios
import axios from ‘axios’
import * as Cookies from ‘js-cookie’;
import {Notification} from “element-ui”;
import { MessageBox } from ‘mint-ui’;
import router from ‘…/…/router’
import config from ‘…/…/assets/ajaxConfig’
import bus from ‘…/…/server/bus’
/**
- Create Axios
*/
var num=0;
var lang=localStorage.language;
if(lang==‘简体中文’ || lang==undefined){
lang=‘zh-cn’
}else{
lang=‘en-us’
}
export const http = axios.create({baseURL:config.url})
var _token= localStorage._token;
http.defaults.headers.common = {
lang,
‘X-Requested-With’: ‘XMLHttpRequest’,
“Content-Type”: “application/json;charset=UTF-8;javascript”,//
Accept: ‘application/json;script’,
Authorization: _token,
};
// let pending = []; //声明一个数组用于存储每个ajax请求的取消函数和ajax标识
// let cancelToken = axios.CancelToken;
// let removePending = (config) => {
// for(let p in pending){
// if(pending[p].u === config.url + ‘&’ + config.method) { //当当前请求在数组中存在时执行函数体
// pending[p].f(); //执行取消操作
// pending.splice(p, 1); //把这条记录从数组中移除
// }
// }
// }
/**
- axios 请求拦截
*/
// http.interceptors.request.use(response=>{
// removePending(response);
// response.cancelToken = new cancelToken(©=>{
// // 这里的ajax标识我是用请求地址&请求方式拼接的字符串,当然你可以选择其他的一些方式
// pending.push({ u: response.url + ‘&’ + response.method, f: c });
// });
// return response;
// },error=>{
// return Promise.reject(error);
// })
/**
-
axios 响应拦截
-
@param requestUrl
-
@returns
*/
http
.interceptors
.response
.use((response) => {
setTimeout(()=>{
if(response.data.code==5001){
localStorage.removeItem(’_token’);
bus.KaTeX parse error: Expected 'EOF', got '}' at position 26: …ut'); }̲ },300) …emit(‘unopen’,response.data.msg);
}
return response.data;
}, (error) => {const {response} = error return response
});
export default function install(Vue) {
Object.defineProperty(Vue.prototype, ‘$http’, {
get() {//get 函数为调用原型方法时调用
router.beforeEach((to,from,next)=>{
if(to.name==‘home’ && from.name==‘login’){//此条件为重新登录后
_token=localStorage._token//重新设置token;
http.defaults.headers.common = {
‘X-Requested-With’: ‘XMLHttpRequest’,
“Content-Type”: “application/json;charset=UTF-8;javascript”,
Accept: ‘application/json’,
Authorization: _token,
lang,
};
}
if((to.path==’/person’ && from.path==’/user/language’)||(to.path==’/login’ && from.path==’/user/language’) ){
lang=localStorage.language
if(lang==‘简体中文’ || lang==undefined){
lang='zh-cn'
}else{
lang='en-us'
}
http.defaults.headers.common = {
lang,
'X-Requested-With': 'XMLHttpRequest',
"Content-Type": "'application/x-www-form-urlencoded;charset=UTF-8;script",//
Accept: 'application/json;script',
Authorization: _token,
};
}
next();
})
return http
}
})
}
下一篇: axios请求设置header信息方法
推荐阅读
-
使用create-react-app+react-router-dom+axios+antd+react-redux构建react项目
-
解决axios会发送两次请求,有个OPTIONS请求的问题
-
详解axios在node.js中的post使用
-
关于axios返回空对象的问题解决
-
基于vue 添加axios组件,解决post传参数为null的问题
-
完美解决axios在ie下的兼容性问题
-
vue axios 给生产环境和发布环境配置不同的接口地址(推荐)
-
vue+vux-ui+axios+mock搭建一个简单vue框架
-
详解Vue+axios+Node+express实现文件上传(用户头像上传)
-
axios 处理 302 状态码的解决方法