1.新建 codeMessage.ts
export default {200: "服务器成功返回请求的数据。",201: "新建或修改数据成功。",202: "一个请求已经进入后台排队(异步任务)。",204: "删除数据成功。",400: "发出的请求有错误,服务器没有进行新建或修改数据的操作。",401: "登录信息已失效,请重新登录。",403: "用户得到授权,但是访问是被禁止的。",404: "发出的请求针对的是不存在的记录,服务器没有进行操作。",405: "请求方法不被允许。",406: "请求的格式不可得。",410: "请求的资源被永久删除,且不会再得到的。",422: "当创建一个对象时,发生一个验证错误。",500: "服务器发生错误,请检查服务器。",502: "网关错误。",503: "服务不可用,服务器暂时过载或维护。",504: "网关超时。",
};
2.新建axios.ts
import axios from "axios";
import { Toast } from "antd-mobile";//三方库,可引入别的
import codeMessage from "./codeMessage";
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
const service = axios.create({baseURL: "/api",timeout: 100000,responseType: "json",headers: { "content-type": "application/json" },
});
/** 设置请求拦截 **/
service.interceptors.request.use((config) => {config.cancelToken = source.token; // 全局添加cancelToken(config as any).headers["Authorization"] = localStorage.getItem("token");return config;},(err) => {return Promise.reject(err);}
);
/** 设置响应拦截 **/
service.interceptors.response.use((response: any): any => {if (response && response?.status) {const { status, data } = response;if (status != 200) {const errorText = codeMessage[response.status] || response.statusText;Toast.show({content: errorText,});return response;}if (data?.code != 200) {Toast.show({content: data?.msg,});}return response;}},(error: any) => {if (axios.isCancel(error)) {// 取消请求的情况下,终端Promise调用链return new Promise(() => {});} else {return Promise.reject(error);}}
);
export default service;
3.新建request.ts
import service from "./axios";
// 方法映射
const methodEnum: Record<"get" | "post" | "upload" | "put",(url: string, params: any) => void
> = {get: (url: string, params = {}) => {return new Promise((resolve, reject) => {service.get(url, { params }).then((res) => {resolve(res.data);}).catch((err) => {reject(err);});});},post: (url: string, data = {}) => {return new Promise((resolve, reject) => {service.post(url, data, {headers: {"Content-Type": "application/json",},}).then((res) => {resolve(res.data);},(err) => {reject(err);});});},put: (url: string, data = {}) => {return new Promise((resolve, reject) => {service.put(url, data, {headers: {"Content-Type": "application/json",},}).then((res) => {resolve(res.data);},(err) => {reject(err);});});},upload: (url: string, files: any) => {return new Promise((resolve, reject) => {const config = {headers: { "Content-Type": "multipart/form-data" },};let data = new FormData();for (const key in files) {if (Object.prototype.hasOwnProperty.call(files, key)) {data.append(key, files[key]);}}data.append("file", files);return service.post(url, data, config).then((res) => {resolve(res);},(err) => {reject(err);});});},
};
type Method =| "get"| "post"| "upload"| "GET"| "POST"| "UPLOAD"| "put"| "PUT";
type RequsetData<T> = {method: Method;params: T;
};
// 请求方法
const requset = (url: string, requsetData: RequsetData<any>): any => {const { method, params } = requsetData;return methodEnum[method.toLocaleLowerCase() as Method](url, params);
};
export default requset;
4.使用方法
import requset from "./request";
// 获取详情
export const detail = (id: string
) => {return request(`/detail/${id}`, {method: "GET",params: {},});
}
type LoginParams = {phone: string;password: String;code: string;
}
// 登录
export const login = (params: LoginParams
) => {return request(`/login`, {method: "POST",params});
}