vue用axios封装request
程序员文章站
2022-03-15 10:25:45
在这里插入代码片``import axios from 'axios';import { MessageBox, Message } from 'element-ui';import store from '@/store';import { getToken } from '@/utils/auth';import { getBlobAsText } from '@/utils/commonFun';// create an axios instanceconst service = ax...
在这里插入代码片
``import axios from 'axios';
import { MessageBox, Message } from 'element-ui';
import store from '@/store';
import { getToken } from '@/utils/auth';
import { getBlobAsText } from '@/utils/commonFun';
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 20000, // request timeout
});
// request interceptor
service.interceptors.request.use(
config => {
// do something before request is sent
if (getToken()) {
// let each request carry token
// ['X-Token'] is a custom headers key
// please modify it according to the actual situation
config.headers['token'] = getToken();
}
return config;
},
error => {
// do something with request error
console.log(error); // for debug
return Promise.reject(error);
},
);
// response interceptor
service.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
async response => {
try {
let res = response.data;
// blob类型错误返回需要手动转为json再做判断
if (response.request.responseType === 'blob') {
let responseJosn = {
code: 0,
};
try {
responseJosn = JSON.parse(await getBlobAsText(res));
// eslint-disable-next-line no-empty
} catch (error) {}
res = {
...responseJosn,
file: res,
};
}
// if the custom code is not 20000, it is judged as an error.
if (
res.code === 0 ||
(response.config.codes && response.config.codes.includes(String(res.code)))
) {
return res;
} else {
// 110: Token expired;
if (res.code === 110) {
// to re-login
MessageBox.alert('登录超时', '系统提示', {
confirmButtonText: '重新登录',
type: 'warning',
}).then(() => {
store.dispatch('LogOut').then(() => {
location.reload();
});
});
} else {
Message({
message: res.message || res.result || res.msg || 'Error',
type: 'error',
duration: 5 * 1000,
});
}
return Promise.reject(new Error(res.msg || res.message || 'Error'));
}
} catch (error) {
return response;
}
},
error => {
console.log('err:1111111111111' + error); // for debug
Message({
message: '网络错误',
type: 'error',
duration: 5 * 1000,
});
return Promise.reject(error);
},
);
export default service;
本文地址:https://blog.csdn.net/luxiaopengyou/article/details/108852302
下一篇: Linux:PCBSD系统的安装