TypeScript对axios的封装
项目中用到了typescript
和axios
,对axios
进行封装:
request.js
:
1 2 3 4 5 6 7 8
| import axios, { AxiosInstance, AxiosRequestConfig, AxiosPromise, AxiosResponse, } from "axios"; const apiBaseUrl = process.env.REACT_APP_API_URL;
|
根据服务端返回的数据格式对返回数据进行约束:
1 2 3 4 5
| export interface ResponseData<T = any> { data?: T, code?: number, msg?: string }
|
创建HttpRequest
类:
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| class HttpRequest { constructor( public baseUrl: string | undefined = apiBaseUrl, public timeout: number = 5000 ) { this.baseUrl = baseUrl; this.timeout = timeout; }
public request(options: AxiosRequestConfig): AxiosPromise { const instance: AxiosInstance = axios.create(); options = this.mergeConfig(options); this.interceptors(instance, options.url); return instance(options); }
private interceptors(instance: AxiosInstance, url?: string) { instance.interceptors.request.use( (config: AxiosRequestConfig) => { let token = auth.getToken(); if (token) { config.headers["Authorization"] = `Bearer ${token}`; } return config; }, (error) => { return Promise.reject(error); } );
instance.interceptors.response.use( async (res: AxiosResponse) => { console.log(res);
const { data } = res; const { code, msg } = data; if (code === 401) { await auth.logout(); window.location.reload(); return Promise.reject({ message: "请重新登录" }); } else { return res; } }, (error) => { return Promise.reject(error); } ); }
private mergeConfig(options: AxiosRequestConfig): AxiosRequestConfig { return { ...options, baseURL: this.baseUrl, timeout: this.timeout }; } }
export default HttpRequest;
|
在api
目录下新建一个index.ts
文件:
index.ts
:
1 2 3
| import HttpRequest from 'utils/request'; export * from 'utils/request' export default new HttpRequest()
|
然后就能在api
目录中写请求接口了,例如auth.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 42
| import http, { ResponseData } from "./index"; import { User } from 'utils/type'; import { AxiosPromise } from 'axios'
interface LoginInformation { username: string; password: string | number; }
interface Response extends User { }
export const userLogin = ( data: LoginInformation ): AxiosPromise<ResponseData<Response>> => { return http.request({ url: `/login`, method: "POST", headers: { "Content-Type": "application/json", }, data: data, }); };
export const userRegister = ( data: LoginInformation ): AxiosPromise<ResponseData> => { return http.request({ url: `/register`, method: "POST", headers: { "Content-Type": "application/json", }, data: data, }); };
|
调用api
:
1 2 3 4 5 6 7 8
| export const login = (data: { username: string; password: string | number}) => { return userLogin(data) .then((res) => { const data = res.data.user; return handleUserResponse(data); }) .catch((error) => Promise.reject(error)); };
|
这样就能用typescript
对请求的数据和返回的数据进行约束,同时对axios也进行了一次封装。