响应拦截器里面
请求重发的注意点是,使用响应里的config作为参数进行重发

  1. axios.interceptors.response.use(
  2. response => {
  3. // 判断是否需要Token刷新
  4. if (...) {
  5. // 刷新Token(可以使用同步操作)
  6. ...
  7. // 将新的Token设置到axios的默认请求头
  8. axios.defaults.headers.common['token'] = newToken;
  9. // 将新的Token设置到重发的请求头
  10. response.config.headers.token = newToken;
  11. // 请求重发
  12. return axios.request(response.config);
  13. }
  14. });

重发逻辑代码

  1. /**
  2. * 响应拦截器
  3. */
  4. let retry = 4; // 重查次数设置
  5. let retryDelay = 1000; // 重查延时ms
  6. axios.interceptors.response.use(
  7. response => {
  8. if (response.data.code == -1) {
  9. // sql 查询出错时返回 -1
  10. // 添加请求次数系数
  11. response.config.requestCount = response.config.requestCount || 1;
  12. // 当前请求次数小于 重查次数,则执行重新查询
  13. if (response.config.requestCount < retry) {
  14. response.config.requestCount++; // 执行重查后,系数+1
  15. let backoff = new Promise(resolve => {
  16. setTimeout(() => {
  17. resolve();
  18. }, retryDelay || 100);
  19. });
  20. return backoff.then(() => {
  21. return axios(response.config);
  22. });
  23. } else {
  24. return response;
  25. }
  26. } else {
  27. return response;
  28. }
  29. },
  30. error => {
  31. // 错误
  32. console.log(error);
  33. return Promise.reject(error);
  34. }
  35. );
  • transformRequest设置是在请求拦截器之后,向服务器发送前进行的
  • transformResponse设置是在响应拦截器之前执行的

9f2c25c81c12e5bc6f48f09159f9fd3.jpg
3737757df75d2e6dda1f0d091986a33.jpg

axios请求配置

  1. {
  2. // `url` 是用于请求的服务器 URL
  3. url: '/user',
  4. // `method` 是创建请求时使用的方法
  5. method: 'get', // 默认值
  6. // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  7. // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  8. baseURL: 'https://some-domain.com/api/',
  9. // `transformRequest` 允许在向服务器发送前,修改请求数据
  10. // 它只能用与 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  11. // 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
  12. // 你可以修改请求头。
  13. transformRequest: [function (data, headers) {
  14. // 对发送的 data 进行任意转换处理
  15. return data;
  16. }],
  17. // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  18. transformResponse: [function (data) {
  19. // 对接收的 data 进行任意转换处理
  20. return data;
  21. }],
  22. // 自定义请求头
  23. headers: {'X-Requested-With': 'XMLHttpRequest'},
  24. // `params` 是与请求一起发送的 URL 参数
  25. // 必须是一个简单对象或 URLSearchParams 对象
  26. params: {
  27. ID: 12345
  28. },
  29. // `paramsSerializer`是可选方法,主要用于序列化`params`
  30. // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  31. paramsSerializer: function (params) {
  32. return Qs.stringify(params, {arrayFormat: 'brackets'})
  33. },
  34. // `data` 是作为请求体被发送的数据
  35. // 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法
  36. // 在没有设置 `transformRequest` 时,则必须是以下类型之一:
  37. // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  38. // - 浏览器专属: FormData, File, Blob
  39. // - Node 专属: Stream, Buffer
  40. data: {
  41. firstName: 'Fred'
  42. },
  43. // 发送请求体数据的可选语法
  44. // 请求方式 post
  45. // 只有 value 会被发送,key 则不会
  46. data: 'Country=Brasil&City=Belo Horizonte',
  47. // `timeout` 指定请求超时的毫秒数。
  48. // 如果请求时间超过 `timeout` 的值,则请求会被中断
  49. timeout: 1000, // 默认值是 `0` (永不超时)
  50. // `withCredentials` 表示跨域请求时是否需要使用凭证
  51. withCredentials: false, // default
  52. // `adapter` 允许自定义处理请求,这使测试更加容易。
  53. // 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
  54. adapter: function (config) {
  55. /* ... */
  56. },
  57. // `auth` HTTP Basic Auth
  58. auth: {
  59. username: 'janedoe',
  60. password: 's00pers3cret'
  61. },
  62. // `responseType` 表示浏览器将要响应的数据类型
  63. // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
  64. // 浏览器专属:'blob'
  65. responseType: 'json', // 默认值
  66. // `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
  67. // 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
  68. // Note: Ignored for `responseType` of 'stream' or client-side requests
  69. responseEncoding: 'utf8', // 默认值
  70. // `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
  71. xsrfCookieName: 'XSRF-TOKEN', // 默认值
  72. // `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
  73. xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值
  74. // `onUploadProgress` 允许为上传处理进度事件
  75. // 浏览器专属
  76. onUploadProgress: function (progressEvent) {
  77. // 处理原生进度事件
  78. },
  79. // `onDownloadProgress` 允许为下载处理进度事件
  80. // 浏览器专属
  81. onDownloadProgress: function (progressEvent) {
  82. // 处理原生进度事件
  83. },
  84. // `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
  85. maxContentLength: 2000,
  86. // `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
  87. maxBodyLength: 2000,
  88. // `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
  89. // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
  90. // 则promise 将会 resolved,否则是 rejected。
  91. validateStatus: function (status) {
  92. return status >= 200 && status < 300; // 默认值
  93. },
  94. // `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
  95. // 如果设置为0,则不会进行重定向
  96. maxRedirects: 5, // 默认值
  97. // `socketPath` 定义了在node.js中使用的UNIX套接字。
  98. // e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
  99. // 只能指定 `socketPath` 或 `proxy` 。
  100. // 若都指定,这使用 `socketPath` 。
  101. socketPath: null, // default
  102. // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  103. // and https requests, respectively, in node.js. This allows options to be added like
  104. // `keepAlive` that are not enabled by default.
  105. httpAgent: new http.Agent({ keepAlive: true }),
  106. httpsAgent: new https.Agent({ keepAlive: true }),
  107. // `proxy` 定义了代理服务器的主机名,端口和协议。
  108. // 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
  109. // 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
  110. // `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
  111. // 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
  112. // 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
  113. proxy: {
  114. protocol: 'https',
  115. host: '127.0.0.1',
  116. port: 9000,
  117. auth: {
  118. username: 'mikeymike',
  119. password: 'rapunz3l'
  120. }
  121. },
  122. // see https://axios-http.com/docs/cancellation
  123. cancelToken: new CancelToken(function (cancel) {
  124. }),
  125. // `decompress` indicates whether or not the response body should be decompressed
  126. // automatically. If set to `true` will also remove the 'content-encoding' header
  127. // from the responses objects of all decompressed responses
  128. // - Node only (XHR cannot turn off decompression)
  129. decompress: true // 默认值
  130. }

https://www.yisu.com/zixun/180955.html
完整的Axios封装
axios原码分析

  1. // 原码:
  2. transformRequest: [function transformRequest(data, headers) {
  3. normalizeHeaderName(headers, 'Content-Type');
  4. if (utils.isFormData(data) ||
  5. utils.isArrayBuffer(data) ||
  6. utils.isBuffer(data) ||
  7. utils.isStream(data) ||
  8. utils.isFile(data) ||
  9. utils.isBlob(data)
  10. ) {
  11. return data;
  12. }
  13. if (utils.isArrayBufferView(data)) {
  14. return data.buffer;
  15. }
  16. if (utils.isURLSearchParams(data)) {
  17. setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
  18. return data.toString();
  19. }
  20. if (utils.isObject(data)) {
  21. setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
  22. return JSON.stringify(data);
  23. }
  24. return data;
  25. }],
  26. transformResponse: [function transformResponse(data) {
  27. if (typeof data === 'string') {
  28. try {
  29. data = JSON.parse(data);
  30. } catch (e) { /* Ignore */ }
  31. }
  32. return data;
  33. }],