带你读《现代TypeScript高级教程》十七、TypeScript封装Fetch(2)https://developer.aliyun.com/article/1348428?groupCode=tech_library
4. 拦截器实现
在这个版本的 FetchService 中,我们把公共的请求逻辑放到了 _request 方法中。我们把方法(GET、POST、PUT、DELETE),URL和可能的请求体传递给 _request 方法,然后它处理所有的共享逻辑,包括运行拦截器,发送请求,处理响应和解析JSON。
export class FetchService { private requestInterceptors: Array<(url: string, options: RequestInit) => void> = []; private responseInterceptors: Array<(response: Response) => void> = []; async get(url: string): Promise { return this._request('GET', url); } async post(url: string, body: any): Promise { return this._request('POST', url, body); } async put(url: string, body: any): Promise { return this._request('PUT', url, body); } async delete(url: string): Promise { return this._request('DELETE', url); } addRequestInterceptor(interceptor: (url: string, options: RequestInit) => void) { this.requestInterceptors.push(interceptor); } addResponseInterceptor(interceptor: (response: Response) => void) { this.responseInterceptors.push(interceptor); } private async _request(method: string, url: string, body?: any): Promise { let options: RequestInit = { method: method, headers: { 'Content-Type': 'application/json' } }; if (body) { options.body = JSON.stringify(body); } this.runRequestInterceptors(url, options); const response = await fetch(url, options); this.runResponseInterceptors(response); if (!response.ok) { throw new Error(response.statusText); } const data: T = await response.json(); return data; } private runRequestInterceptors(url: string, options: RequestInit) { this.requestInterceptors.forEach(interceptor => interceptor(url, options)); } private runResponseInterceptors(response: Response) { this.responseInterceptors.forEach(interceptor => interceptor(response)); }}
示例:
const fetchService = new FetchService(); // 添加一个请求拦截器 fetchService.addRequestInterceptor((url, options) => { options.headers = { ...options.headers, 'Authorization': 'Bearer ' + localStorage.getItem('token') };}); // 添加一个响应拦截器 fetchService.addResponseInterceptor(response => { if (response.status === 401) { console.error('Unauthorized!'); }});
5.总结
这是一个基础的实现,其它可以根据你的需求来进行修改或扩展。