import axios ,{AxiosInstance,AxiosRequestConfig,AxiosResponse} from 'axios'
export class Request {
public static axiosInstance:AxiosInstance;
public static init() {
this.axiosInstance = axios.create({
baseURL:'/api',
timeOut:6000
});
// 初始化拦截器
this.initInterceptors();
return axios
}
// 初始化拦截器
public static initInterceptors() {
// 设置post请求头
this.axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-ww-form-urlencoded';
this.axiosInstance.interceptors.request.use(
(config:AxiosRequestConfig) => {
// 登录流程控制中,根据本地是否存在token判断用户的登录情况
const token = localStorage.getItem('ACCESS_TOKEN');
if(token){
config.headers.Authorization = 'Bearer' + token;
}
return config
},
(error) => {
console.log(error)
}
);
this.axiosInstance.interceptors.response.use(
(response:AxiosResponse) => {
if(response.status === 200){
return response;
}else {
Request.errorHandle(response);
return response
}
},
(error) => {
const {response} = error;
if(response){
Request.errorHandle(response);
return Promise.reject(response.data);
}else {
console.log("网络连接异常,请稍后再试!")
}
}
)
};
public static errorHandle(res){
switch(res.status){
case 401:
break;
case 403:
break;
case 404:
break;
default:
console.log('报错了')
}
}
}
// 使用
// export function login (params) {
// return Request.axiosInstance({
// url:'/xxxxx',
// method:'post',
// data:params
// })
// }
//注:处理响应数据 (示例代码,实际可直接直接使用await-to-js)
网友评论