vue 项目axios封装
import axios from "axios";
import qs from "qs";
import Vue from "vue";
import { Dialog, Toast } from "cube-ui";
import router from "../router";
Vue.use(Dialog);
Vue.use(Toast);
axios.interceptors.request.use(
config => {
if (sessionStorage.getItem("token")) {
config.headers.token = sessionStorage.getItem("token");
}
return config;
},
error => {
return Promise.reject(error);
}
);
axios.interceptors.response.use(
response => {
return response;
},
error => {
return Promise.resolve(error.response);
}
);
function checkStatus(response) {
// loading
// 如果http状态码正常,则直接返回数据
if (
response &&
(response.status === 200 ||
response.status === 304 ||
response.status === 400)
) {
return response;
// 如果不需要除了data之外的数据,可以直接 return response.data
} else {
// 如果状态错误,删除token,删除token,路由守卫就会判断。
sessionStorage.removeItem("token");
return {
status: 404,
msg: "网络异常"
};
}
}
function checkCode(res) {
// 如果code异常(这里已经包括网络错误,服务器错误,后端抛出的错误),可以弹出一个错误提示,告诉用户
if (res.status != 404) {
if (res.data.code == "1" || res.data.code == "0") {
return res.data;
} else {
Dialog.$create({
type: "confirm",
icon: "",
title: "",
content: res.data.msg,
confirmBtn: {
text: "去登录",
active: true,
disabled: false,
href: "javascript:;"
},
cancelBtn: {
text: "取消",
active: false,
disabled: false,
href: "javascript:;"
},
onConfirm: () => {
router.push({ name: "login" });
},
onCancel: () => {}
}).show();
return;
}
} else {
Toast.$create({
txt: "网络错误",
type: "txt"
}).show();
}
}
export default {
post(url, data) {
return axios({
method: "post",
baseURL: "/apis/api-app/",
url,
data: qs.stringify(data),
timeout: 2000,
headers: {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
}
})
.then(response => {
return checkStatus(response);
})
.then(res => {
return checkCode(res);
});
}
};
1、token的配置
2、返回code的判断(接口返回成功的code,是和后台商定的。)
3、弹窗的引用
4、路由的跳转