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)
request.js
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 错误信息如下: app.js:669 Uncaught Error: [🍍]: getActivePinia wa...
- 最近搭建template项目使用了axios用于接口请求,由于第一次自己搭建项目,遇到的坑比较多,原版也都是英文,...
- vue-element-template 如何使用官方request.js请求 许多新手在使用VUE-elemen...