封装axios拦截器
创建service文件夹,创建入口文件index.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
import XRequest from './request' import { BASE_URL, TIME_OUT } from './request/config'
const xRequest = new XRequest({ baseURL: BASE_URL, timeout: TIME_OUT, interceptors: { requestInterceptor: (config) => { console.log('请求成功拦截')
return config }, requestInterceptorCatch: (err) => { console.log('请求失败拦截') return err }, responseInterceptor: (res) => { console.log('响应成功拦截') return res }, responseInterceptorCatch: (err) => { console.log('响应失败拦截') return err } } })
export default xRequest
|
创建request文件夹,创建入口文件index.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import axios from 'axios' import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios' interface XRequestInterceptors { requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfig requestInterceptorCatch?: (error: any) => any responseInterceptor?: (res: AxiosResponse) => AxiosResponse responseInterceptorCatch?: (error: any) => any }
interface XRequestConfig extends AxiosRequestConfig { interceptors?: XRequestInterceptors } class XRequest { instance: AxiosInstance interceptors?: XRequestInterceptors constructor(config: XRequestConfig) { this.instance = axios.create(config)
this.interceptors = config.interceptors
this.instance.interceptors.request.use( this.interceptors?.requestInterceptor, this.interceptors?.requestInterceptorCatch ) this.instance.interceptors.response.use( this.interceptors?.responseInterceptor, this.interceptors?.responseInterceptorCatch ) } request(config: AxiosRequestConfig): void { this.instance.request(config).then((res) => { console.log(res) }) } } export default XRequest
|
可选,在/request创建config.ts文件
1 2 3 4 5 6 7 8 9 10 11 12
| let BASE_URL = '' const TIME_OUT = 10000
if (process.env.NODE_ENV === 'development') { BASE_URL = 'https://backup.fastmock.site/mock/3e6d55f607e287c78c97f316f7dd6ff8/api' } else if (process.env.NODE_ENV === 'production') { BASE_URL = 'http://152.136.185.210:5000' } else if (process.env.NODE_ENV === 'test') { BASE_URL = 'eawefa' } export { BASE_URL, TIME_OUT }
|