粒子研究院后台前端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

132 lines
4.0 KiB

import axios from "axios";
import util from "@/libs/util";
import router from "@/router/index";
import Setting from "@/setting";
import store from '@/store'
const service = axios.create({
baseURL: Setting.apiBaseURL,
timeout: 10000000
});
// post请求头
service.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
// service.defaults.withCredentials = true
// 请求拦截器
service.interceptors.request.use(config => {
util.getToken();
let token = util.local.get(Setting.tokenKey);
config.headers.captcha = ''
return config;
}, err => {
util.errorMsg({
message: "退出登陆",
onClose: function() {
store.dispatch('user/logout')
}
});
return Promise.reject(err);
});
// 响应拦截器
service.interceptors.response.use(
response => {
const res = response.data;
if (res.code == 200) {
return Promise.resolve(res).catch(e => {});
} else {
util.errorMsg(res.msg);
return Promise.reject(res)
// return Promise.resolve(res).catch(e => {});
}
},
// 服务器状态码不是200的情况
error => {
if (error.response.status) {
switch (error.response.status) {
// 401: 未登录
// 未登录则跳转登录页面,并携带当前页面的路径
// 在登录成功后返回当前页面,这一步需要在登录页操作。
case 401:
util.local.remove(Setting.storeKey);
util.local.remove(Setting.tokenKey);
util.errorMsg("登录过期,请重新登录");
setTimeout(() => {
store.dispatch('user/logout')
}, 1000);
break;
case 500:
util.errorMsg("网络错误");
break;
// 403 token过期
// 登录过期对用户进行提示
// 清除本地token和清空vuex中token对象
// 跳转登录页面
case 403:
util.local.remove(Setting.storeKey);
util.local.remove(Setting.tokenKey);
util.errorMsg("登录过期,请重新登录");
// 清除token
// store.commit('loginSuccess', null);
// 跳转登录页面,并将要浏览的页面fullPath传过去,登录成功后跳转需要访问的页面
setTimeout(() => {
store.dispatch('user/logout')
}, 1000);
break;
// 404请求不存在
case 404:
util.errorMsg("网络请求不存在!");
break;
// 其他错误,直接抛出错误提示
default:
util.errorMsg(error.response.data.message);
Promise.reject(res);
}
return Promise.reject(error.response);
}
}
);
function get(url, params) {
return new Promise((resolve, reject) => {
service.get(url, { params: params }).then(res => {
resolve(res);
}).catch(err => {
reject(err);
});
});
}
function post(url, params) {
return new Promise((resolve, reject) => {
service.post(url, params).then(res => {
resolve(res);
}).catch(err => {
reject(err.data);
});
});
}
function del(url, params) {
return new Promise((resolve, reject) => {
service.delete(url, {
data: params
}).then(res => {
resolve(res);
}).catch(err => {
reject(err.data);
});
});
}
function put(url, params) {
return new Promise((resolve, reject) => {
service.put(url, params).then(res => {
resolve(res);
}).catch(err => {
reject(err.data);
});
});
}
export { get, post, del, put };