import sv from “./static-variables”;//引入静态变量
import router from “…/router/index”;//引入静态变量
import vueAxios from “axios”;//引入axios
vueAxios.defaults.withCredentials = true;//解决跨域问题
//创建axios实例
let instance = vueAxios.create({
baseURL: sv.SERVER_URL,
timeout: 30000,
responsetype: ‘json’,
transformRequest: [function (data, headers) {
//依自己的需求对请求数据进行处理
if (!data) {
return data;
}
//复杂实体
if (typeof data === ‘string’) {
//修改请求头部
headers[‘post’][‘Content-Type’] = ‘application/json; charset=UTF-8’;
return data;
} else {
// 普通对象,通过URLSearchParams传参
let params = new URLSearchParams();
for (let i in data) {
if (Object.prototype.hasOwnProperty.call(data, i)) { //过滤
params.append(i, data[i]);
}
}
return params;
}
}],
headers: {‘requestType’: ‘SERVER’},
});
//封装post和get请求
function fetch(url, auxiosmethod, param, isLoading,_config) {
return new Promise((resolve, reject) => {
param = !param ? {} : param;
if (auxiosmethod === “post”) {//post请求
instance.post(url, param, _config).then(response => {
resolve(response);
}).catch((error) => {
reject(error);
});
} else if (auxiosmethod === “get”) {//get请求
instance.get(url, param).then(response => {
resolve(response);
}).catch((error) => {
reject(error);
});
}
})
}
//axios请求拦截;(请求时加上token)
instance.interceptors.request.use(
config => {
// let token = storage.getJsonLocalStorageItem(sv.USER_TOKEN);
// if(token){
// config.headers[‘Authorization’] =token;
// }else {
// router.push(\”/login\”);
// }
return config
}
);
//axios响应拦截;(根据状态码跳不同页面)
instance.interceptors.response.use(
response => {
if(response.data.code=401){
router.push(\”/403\”);
}
return response;
},
error=>{
// if(error.response.status=500){
// router.push(\”/500\”);
// }else if(error.response.status=404){
// router.push(\”/404\”);
// }else if(error.response.status=401){
// router.push(\”/\”);
// }
return error;
}
);
export default {
/**
- post请求
- @param url 请求地址
- @param param 请求参数(复杂实体要序列化)
- @param isLoading 不开loading false,开loading true
- @param _config 特殊请求更改请求头配置
- @return {*}
/
post(url, param, isLoading,_config) {
return fetch(url, “post”, param,isLoading, _config)
},
/* - get请求
- @param url 请求地址
- @param param 请求参数(复杂实体要序列化)
- @param isLoading 不开loading false,开loading true
- @return {*}
*/
get(url, param, isLoading){
return fetch(url, “get”, param, isLoading)
},
}