99 lines
2.6 KiB
TypeScript
99 lines
2.6 KiB
TypeScript
/*
|
||
* Copyright (c) 2020. bmy
|
||
*/
|
||
|
||
import axios, { AxiosInstance, AxiosError, AxiosRequestConfig } from "axios";
|
||
import { IndexUtils } from "@utils/index.utils";
|
||
|
||
/**
|
||
* axios的封装
|
||
*/
|
||
export class AxioDao {
|
||
instance: AxiosInstance;
|
||
|
||
public constructor() {
|
||
this.instance = axios.create({
|
||
baseURL: IndexUtils.CheckAjaxUrl(),
|
||
timeout: 10000,
|
||
headers: {
|
||
"Content-Type": "application/json"
|
||
}
|
||
});
|
||
this.ResponseInterceptor();
|
||
this.RequestInterceptor();
|
||
}
|
||
|
||
public async get(params: AxiosRequestConfig): Promise<any> {
|
||
return await this.instance.get(<string>params.url, {
|
||
params: params.data,
|
||
headers: Object.assign({ Authorization: localStorage.getItem("token") }, params.headers)
|
||
});
|
||
}
|
||
|
||
public async post(params: AxiosRequestConfig): Promise<any> {
|
||
return await this.instance.post(<string>params.url, params.data, {
|
||
headers: Object.assign({ Authorization: localStorage.getItem("token") }, params.headers)
|
||
})
|
||
}
|
||
|
||
/**
|
||
* Put 请求
|
||
* 请求参数请参考接口:RequestParams
|
||
* @param params
|
||
*/
|
||
public async put(params: AxiosRequestConfig): Promise<any> {
|
||
return await this.instance.put(<string>params.url, params.data)
|
||
}
|
||
|
||
/**
|
||
* delete 请求
|
||
* 请求参数请参考接口:RequestParams
|
||
* @param params
|
||
*/
|
||
public async delete(params: AxiosRequestConfig): Promise<any> {
|
||
return await this.instance.delete(<string>params.url, { params: params.data })
|
||
}
|
||
|
||
/**
|
||
* 响应拦截器
|
||
* @constructor
|
||
*/
|
||
public async ResponseInterceptor(): Promise<any> {
|
||
this.instance.interceptors.response.use(
|
||
(response: any) => {
|
||
return response.data.result;
|
||
},
|
||
(error: AxiosError) => {
|
||
console.log(`
|
||
❌ 请求错误 ❌
|
||
1、基地址: ${error.config.baseURL}
|
||
2、短地址: ${error.config.url}
|
||
3、请求 方式: ${error.config.method}
|
||
4、请求 参数: ${JSON.stringify(error.config.params)}
|
||
5、请求 头 : ${JSON.stringify(error.config.headers)}
|
||
|
||
------------------------------------------------------------
|
||
|
||
6、错误信息为: ${error.message}
|
||
7、错误代码为: ${error.stack}
|
||
`);
|
||
return Promise.reject(error)
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 添加请求拦截器
|
||
* @constructor
|
||
*/
|
||
public async RequestInterceptor(): Promise<any> {
|
||
this.instance.interceptors.request.use((config: any) => {
|
||
return config
|
||
}, function (error: AxiosError) {
|
||
return Promise.reject(error)
|
||
})
|
||
}
|
||
|
||
}
|
||
|
||
export default new AxioDao();
|