axios请求的封装是项目中最常见的应用。鉴于此。我们将封装一个基于axios的常见请求库,
它要满足如下几个功能:
1能手动传入参数,控制当前请求是否需要加载中这样的loading层
2满足get、post、put、delete这四种常见的请求方式
3 对于post 请求,集成普通表单上传和图片上传两种功能(put 请求也可以实现文件上传)
4 处理登录过期和权限拦截逻辑
(本实例中 loading层是自己写的插件)
import axios from "axios"
import router from "@r/index.js"
import { db } from "@u/utils" //db--->处理localStorage数据的方法集合
import qs from "qs"
let loadingInstance = Vue.prototype.$sLoading; //自己写的loading插件,也可以引用第三方组件库的Message函数,比如element-ui 的Message
let config = {
timeout: 5000,
baseURL: "",
};
const Http = axios.create(config);
// 添加请求拦截器
Http.interceptors.request.use((config) => {
let type = Object.prototype.toString.call(config.data)
if (config.method == 'post' || config.method == 'put') {
if (type == "[object FormData]") { //处理图片文件
if (config.data.loading) { //如果请求接口时传入了loading参数且值为true,则弹层loading提示
loadingInstance.open({ text: "文件上传中,请稍后", type: "loading" });
}
config.headers = { "Content-Type": "multipart/form-data" }
} else {
loadingInstance.open() //处理普通表单
config.headers = { "Content-Type": "application/x-www-form-urlencoded" }
config.data = qs.stringify(config.data)
}
} else {
if (config.params.loading) {
loadingInstance.open();
}
config.data = qs.stringify(config.data)
}
return config;
});
// 添加响应拦截器
Http.interceptors.response.use(
(response) => {
loadingInstance.close();
return response.data;
},
(error) => {
console.log("error:", error);
if (
error.code === "ECONNABORTED" ||
error.message === "Network Error" ||
error.message.includes("timeout")
) {
loadingInstance.open({ type: "error", text: "当前网络错误" });
}
//错误处理
let code = error.response.status;
if (code == 200) {
console.log(200);
} else if (code == 403) {
//处理token过期问题
loadingInstance.open({
type: "error",
text: "登录已过期,请重新登录",
});
db.ls.clear()
db.ss.clear()
router.replace("/")
} else {
loadingInstance.open({
type: "error",
text: error.response.data,
});
}
return Promise.reject(error);
}
);
// loading: true:请求接口时出现加载提示,false反之
function request(url, method = "GET", params = {}, loading = false) {
let Method = method.toLowerCase()
if (Method == "get"||Method == "delete") {
params = { ...params, loading }
return Http[Method](url, { params });
} else if(Method == "post"||Method == "put"){
let data = Object.assign(params, { loading })
return Http[Method](url, data);
}
}
export default request;