{"id":235,"date":"2025-01-09T11:28:00","date_gmt":"2025-01-09T03:28:00","guid":{"rendered":"https:\/\/mitongxue.cn\/?p=235"},"modified":"2026-06-05T11:40:55","modified_gmt":"2026-06-05T03:40:55","slug":"axios%e7%ae%80%e5%8d%95%e5%b0%81%e8%a3%85","status":"publish","type":"post","link":"https:\/\/mitongxue.cn\/index.php\/2025\/01\/09\/axios%e7%ae%80%e5%8d%95%e5%b0%81%e8%a3%85\/","title":{"rendered":"axios\u7b80\u5355\u5c01\u88c5"},"content":{"rendered":"\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"276\" height=\"149\" src=\"https:\/\/mitongxue.cn\/wp-content\/uploads\/2026\/06\/image-33.png\" alt=\"\" class=\"wp-image-236\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">request.ts<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import type {\n  AxiosInstance,\n  AxiosRequestConfig,\n  InternalAxiosRequestConfig,\n  AxiosError,\n  AxiosResponse\n} from \"axios\";\nimport axios from \"axios\";\nimport event from \".\/eventEmitter\";\nimport type { ResultData } from \".\/interface\";\n\nclass Request {\n  private service: AxiosInstance;\n\n  constructor(config: AxiosRequestConfig) {\n    this.service = axios.create(config);\n    \n    \/** \u8bf7\u6c42\u62e6\u622a\u5668 *\/\n    this.service.interceptors.request.use(\n      (config: InternalAxiosRequestConfig) => {\n        \/\/ \u5728\u8bf7\u6c42\u53d1\u9001\u65f6\u5904\u7406\u4e00\u4e9b\u5185\u5bb9\n        \/\/ \u6bd4\u5982\u5728\u8bf7\u6c42\u5934\u4e2d\u6dfb\u52a0 token\n        const token = localStorage.getItem(\"token\");\n        if (token) { \n          config.headers.Authorization = \"Bearer \" + token;\n        }\n        return config;\n      },\n      (error: AxiosError) => {\n        return Promise.reject(error);\n      }\n    );\n    \/** \u54cd\u5e94\u62e6\u622a\u5668 *\/\n    this.service.interceptors.response.use(\n      (response: AxiosResponse) => { \n        const { data } = response;\n        \n        if (data.code === RequestEnums.LOGINTIMEOUT) { \n          event.emit(\"API:SESSION_EXPIRED\");\n          return Promise.reject(data);\n        }\n        if (data.code !==  RequestEnums.SUCCESS) { \n          event.emit(\"API:INVALID\");\n          return Promise.reject(data);\n        }\n        return data;\n      },\n      (error: AxiosError) => { \n        event.emit(\"API:NETWORK_ERROR\");\n        return Promise.reject(error)\n      }\n    );\n  }\n\n  get&lt;T>(url: string, params?: object): Promise&lt;ResultData&lt;T>> { \n    return this.service.get(url, { params });\n  }\n  post&lt;T>(url: string, params?: object): Promise&lt;ResultData&lt;T>> { \n    return this.service.post(url, params);\n  }\n  put&lt;T>(url: string, params?: object): Promise&lt;ResultData&lt;T>> { \n    return this.service.put(url, params);\n  }\n  delete&lt;T>(url: string, params?: object): Promise&lt;ResultData&lt;T>> { \n    return this.service.delete(url, { params });\n  }\n}\n\nenum RequestEnums {\n  TIMEOUT = 10000, \/\/ \u8bf7\u6c42\u8d85\u65f6\n  FAIL = 500, \/\/ \u670d\u52a1\u5668\u5f02\u5e38\n  INVALID = 400, \/\/ \u53c2\u6570\u9519\u8bef\n  LOGINTIMEOUT = 401, \/\/ \u767b\u5f55\u8d85\u65f6\n  SUCCESS = 200, \/\/ \u8bf7\u6c42\u6210\u529f\n}\n\nconst config: AxiosRequestConfig = {\n  baseURL: \"\/api\",\n  timeout: RequestEnums.TIMEOUT as number,\n  withCredentials: true,\n};\n\nconst request = new Request(config);\n\nexport default request;\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">eventEmitter.ts<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>const eventNames = &#91;\"API:UN_AUTHORIZED\", \"API:INVALID\", \"API:NETWORK_ERROR\", \"API:SESSION_EXPIRED\"] as const;\ntype EventName = typeof eventNames&#91;number];\n\n\/\/ \u53d1\u5e03\u8ba2\u9605\u6a21\u5f0f\nclass EventEmitter { \n  private listeners: Record&lt;EventName, Set&lt;Function>> = {\n    \"API:UN_AUTHORIZED\": new Set,\n    \"API:INVALID\": new Set,\n    \"API:NETWORK_ERROR\": new Set,\n    \"API:SESSION_EXPIRED\": new Set\n  }\n\n  \/\/ \u76d1\u542c\u4e8b\u4ef6\uff0c\u548cdom\u6ce8\u518c\u4e8b\u4ef6\u662f\u4e00\u4e2a\u9053\u7406\uff0c\u5c06\u6765\u67d0\u4e2a\u4e8b\u4ef6\u53d1\u751f\u7684\u65f6\u5019\u9700\u8981\u8fd0\u884c\u54ea\u4e2a\u51fd\u6570\n  on(eventName: EventName, listener: Function) { \n    this.listeners&#91;eventName].add(listener);\n  }\n\n  \/\/ \u89e6\u53d1\u4e8b\u4ef6\uff0c\u5f53\u67d0\u4e2a\u4e8b\u4ef6\u53d1\u751f\u7684\u65f6\u5019\uff0c\u8c03\u7528\u76d1\u542c\u7684\u51fd\u6570\n  emit(eventName: EventName, ...args: any&#91;]) { \n    this.listeners&#91;eventName].forEach(listener => listener(...args));\n  }\n}\n\nexport default new EventEmitter();<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">api\/interface\/index.ts<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>export interface Result { \n  code: number;\n  msg: string;\n  success: boolean;\n}\n\nexport interface ResultData&lt;T = any> extends Result { \n  data?: T;\n}\n\nexport interface Sales{\n  _id: string;\n  name: string;\n  value: number;\n}\n\nexport interface Trends { \n  _id: string;\n  name: string;\n  data: number&#91;];\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">api\/modules\/sales.ts<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import type { Sales } from \"..\/interface\";\nimport request from \"..\/request\";\n\nexport const getSalesList = () => { \n  return request.get&lt;Sales&#91;]>('\/api\/sales\/list');\n}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>request.ts eventEmitter.t..<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[16,13,11],"tags":[],"class_list":["post-235","post","type-post","status-publish","format-standard","hentry","category-js","category-vue","category-front"],"featured_image_urls":{"full":"","thumbnail":"","medium":"","medium_large":"","large":"","1536x1536":"","2048x2048":""},"author_info":{"info":["\u9648 \u67d0\u4eba"]},"category_info":"<a href=\"https:\/\/mitongxue.cn\/index.php\/category\/front\/js\/\" rel=\"category tag\">JS<\/a> <a href=\"https:\/\/mitongxue.cn\/index.php\/category\/front\/vue\/\" rel=\"category tag\">Vue<\/a> <a href=\"https:\/\/mitongxue.cn\/index.php\/category\/front\/\" rel=\"category tag\">\u524d\u7aef<\/a>","tag_info":"\u524d\u7aef","comment_count":"0","_links":{"self":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/235","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/comments?post=235"}],"version-history":[{"count":1,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/235\/revisions"}],"predecessor-version":[{"id":237,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/235\/revisions\/237"}],"wp:attachment":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/media?parent=235"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/categories?post=235"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/tags?post=235"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}