vue中axios请求的封装
程序员文章站
2022-07-02 12:30:14
...
创建utils文件夹
安装axios
$ npm install axios -S
引入如下两个文件
1.axios.js
const VueAxios = {
vm: {},
// eslint-disable-next-line no-unused-vars
install(Vue, instance) {
if (this.installed) {
return;
}
this.installed = true;
if (!instance) {
// eslint-disable-next-line no-console
console.error("You have to install axios");
return;
}
Vue.axios = instance;
Object.defineProperties(Vue.prototype, {
axios: {
get: function get() {
return instance;
}
},
$http: {
get: function get() {
return instance;
}
}
});
}
};
export { VueAxios };
2.引入request.js文件
import axios from "axios";
import { VueAxios } from "./axios";
// import qs from "qs"; //需安装,按需引入
// 创建 axios 实例
/* eslint-disable */
const service = axios.create({
baseURL:'http://192.168.199.195:8080', //请求地址公共部分
timeout: 6000, // 请求超时时间
withCredentials: true, //配置跨域
// transformRequest: [
// function(data) {
// // 允许向服务器发送前,修改稿请求数据
// return qs.stringify(data); // 对data进行转换
// }
// ]
});
const err = error => { //响应异常拦截
if (error.response) {
const token = window.localStorage.getItem("token");
if (error.response.status === 403) {
...
}
if (error.response.status === 401) { //!(data.result && data.result.isLogin)
if (token) {
window.localStorage.removeItem("token");
}else{
....
}
}
}
return Promise.reject(error);
};
// request interceptor
service.interceptors.request.use(config => { //请求拦截
const token = window.localStorage.getItem("token");
if (token) {
config.headers["Authorization"] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
}
return config;
}, err);
// response interceptor
service.interceptors.response.use(response => { //响应拦截
return response.data;
}, err)
const installer = {
vm: {},
install(Vue) {
Vue.use(VueAxios, service);
}
};
export { installer as VueAxios, service as axios };