config文件

  1. import http from 'http';
  2. import https from 'https';
  3. import qs from 'qs';
  4. import { AxiosResponse, AxiosRequestConfig } from 'axios';
  5. const axiosConfig: AxiosRequestConfig = {
  6. baseURL: '/',
  7. // 请求后的数据处理
  8. transformResponse: [
  9. function(data: AxiosResponse) {
  10. return data;
  11. },
  12. ],
  13. // 查询对象序列化函数
  14. paramsSerializer: function(params: any) {
  15. return qs.stringify(params);
  16. },
  17. // 请求超时时间
  18. timeout: 3000,
  19. // 跨域是否带token
  20. withCredentials: true,
  21. responseType: 'json',
  22. // xsrf 设置
  23. xsrfCookieName: 'XSRF-TOKEN',
  24. xsrfHeaderName: 'X-XSRF-TOKEN',
  25. validateStatus: function(status: number) {
  26. return status >= 200 && status < 300;
  27. },
  28. };
  29. export default axiosConfig;

返回值的TS声明文件

  1. declare namespace Ajax {
  2. // axios 返回数据
  3. export interface AxiosResponse {
  4. data: AjaxResponse;
  5. }
  6. // 请求接口数据
  7. export interface AjaxResponse {
  8. code: number;
  9. data: any;
  10. message: string;
  11. success: boolean;
  12. }
  13. }

请求主体

  1. import axios, { AxiosRequestConfig, AxiosError } from 'axios';
  2. import config from './config';
  3. import Cookies from 'universal-cookie';
  4. export const cookies = new Cookies({});
  5. interface Item {
  6. url: string;
  7. cancel: () => void;
  8. }
  9. let pending: Array<Item> = [];
  10. const CancelToken = axios.CancelToken;
  11. const removePending = (config: AxiosRequestConfig) => {
  12. for (const p in pending) {
  13. if (pending.hasOwnProperty(p)) {
  14. const list = pending[p];
  15. if (list.url === config.url + '&request_type=' + config.method) {
  16. list.cancel();
  17. pending.splice(+p, 1);
  18. }
  19. }
  20. }
  21. };
  22. const service = axios.create(config);
  23. // 添加请求拦截器
  24. service.interceptors.request.use(
  25. config => {
  26. removePending(config);
  27. config.cancelToken = new CancelToken(c => {
  28. pending.push({
  29. url: config.url + '&request_type=' + config.method,
  30. cancel: c,
  31. });
  32. });
  33. return config;
  34. },
  35. error => {
  36. return Promise.reject(error);
  37. }
  38. );
  39. // 返回状态判断(添加响应拦截器)
  40. service.interceptors.response.use(
  41. res => {
  42. removePending(res.config);
  43. return res;
  44. },
  45. error => {
  46. return Promise.reject(error);
  47. }
  48. );
  49. /**
  50. * axios请求错误统一处理函数
  51. */
  52. function errorHandler(error: AxiosError): Ajax.AjaxResponse {
  53. if (error.response) {
  54. return {
  55. success: false,
  56. message: error.response.data.message,
  57. code: 50000,
  58. data: null,
  59. };
  60. }
  61. return {
  62. success: false,
  63. code: 40400,
  64. data: null,
  65. message: error.message,
  66. };
  67. }
  68. /**
  69. * 封装了几个通用的请求函数
  70. */
  71. export default {
  72. get: function(url: string, params: any) {
  73. const accessToken = cookies.get('token');
  74. if (!accessToken) {
  75. throw new Error('登录已失效,请重新登录');
  76. }
  77. // params添加到url中
  78. return service
  79. .get(url, {
  80. params,
  81. headers: {
  82. accessToken,
  83. },
  84. })
  85. .then((res: Ajax.AxiosResponse) => {
  86. return res.data;
  87. })
  88. .catch(errorHandler);
  89. },
  90. del: function(url: string, params: any) {
  91. const accessToken = cookies.get('token');
  92. if (!accessToken) {
  93. throw new Error('登录已失效,请重新登录');
  94. }
  95. return service
  96. .delete(url, {
  97. params,
  98. headers: {
  99. accessToken,
  100. },
  101. })
  102. .then((res: Ajax.AxiosResponse) => {
  103. return res.data;
  104. })
  105. .catch(errorHandler);
  106. },
  107. // 无需token
  108. fetch: function(url: string, data: any) {
  109. return service
  110. .post(url, data)
  111. .then((res: Ajax.AxiosResponse) => {
  112. return res.data;
  113. })
  114. .catch(errorHandler);
  115. },
  116. post: function(url: string, data: any, params: any) {
  117. const accessToken = cookies.get('token');
  118. if (!accessToken) {
  119. throw new Error('登录已失效,请重新登录');
  120. }
  121. // data添加到请求体body中
  122. return service
  123. .post(url, data, {
  124. params,
  125. headers: {
  126. accessToken,
  127. },
  128. })
  129. .then((res: Ajax.AxiosResponse) => {
  130. return res.data;
  131. })
  132. .catch(errorHandler);
  133. },
  134. put: function(url: string, data: any, params: any) {
  135. const accessToken = cookies.get('token');
  136. if (!accessToken) {
  137. throw new Error('登录已失效,请重新登录');
  138. }
  139. return service
  140. .put(url, data, {
  141. params,
  142. headers: {
  143. accessToken,
  144. },
  145. })
  146. .then((res: Ajax.AxiosResponse) => {
  147. return res.data;
  148. })
  149. .catch(errorHandler);
  150. },
  151. };