企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ---- ### Axios 文档 https://axios-http.com/zh/docs/req_config https://zhuanlan.zhihu.com/p/607327691 https://www.zhihu.com/question/621510353 ---- ### 封装 **封装:** ```javascript import axios from "axios"; export type Result<T> = { code: number; data: T; msg?: string; }; const instance = axios.create({ baseURL: process.env.VUE_APP_BASE_API || location.origin, timeout: 30000, headers: { "X-Custom-Header": "foobar" }, }); // 添加请求拦截器 instance.interceptors.request.use( function (config) { // 在发送请求之前做些什么 config.headers["X-Custom-Header"] = "sf"; // if (token) { // config.headers!['AdminToken'] = token // } return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); } ); // 添加响应拦截器 instance.interceptors.response.use( (response) => { // 对响应数据做点什么 // nProgress.done() const { data, code, msg } = response.data as Result<any>; if (code == 0) { return data; } else { // Message.warning({ // message: msg as string, // duration: 2 * 1000, // }) return Promise.reject(msg); } // return response; }, (error) => { // 对响应错误做点什么 // nProgress.done(); const { message, name } = error; if (name !== "CanceledError") { let msg; if (message === "Network Error") { msg = "连接异常"; } else if (message.includes("timeout")) { msg = "请求超时"; } else if (message.includes("Request failed with status code")) { msg = "接口错误"; } // Message.error({ // message: msg || "未知错误", // duration: 1.5 * 1000, // }); } return Promise.reject(error); } ); export const request = function (url: string, method = "get", params: object = {}, data: object = {}, config: any = {}): Promise<{ token: string; expire?: number }> { return instance(url, { method, params, data, ...config }); }; export const get = function (url: string, params: object = {}, config: any = {}): Promise<{ token: string; expire?: number }> { return instance.get(url, { params, ...config }); }; export const post = function (url: string, data: object = {}, config: any = {}): Promise<{ token: string; expire?: number }> { return instance.post(url, data, { ...config }); }; export default instance; ``` **使用示例:** ```javascript // then catch function getUser(userId: Number, success: Function = () => {}) { const controller = new AbortController(); const cancelRequest = () => { controller.abort(); }; get("/user", { id: 1 }, { signal: controller.signal }) .then(function (data) { success(data); }) .catch(function (error) { if (axios.isCancel(error)) { console.log("Request canceled", error.message); } else { // 处理错误 console.error(error); } }) .finally(function () { // done response }); // 取消请求 setTimeout(() => { cancelRequest(); }, 500); } getUser(2, (data: any) => { console.log(data); }); // async await async function getUser2(userId: Number, success: Function = () => {}) { try { let data = await get("/user", { id: 1 }); success(data); } catch (error) { console.error(error); } } getUser2(2, (data: any) => { console.log(data); }); ```