dispatchRequest.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict';
  2. import transformData from './transformData.js';
  3. import isCancel from '../cancel/isCancel.js';
  4. import defaults from '../defaults/index.js';
  5. import CanceledError from '../cancel/CanceledError.js';
  6. import AxiosHeaders from '../core/AxiosHeaders.js';
  7. import adapters from '../adapters/adapters.js';
  8. /**
  9. * Throws a `CanceledError` if cancellation has been requested.
  10. *
  11. * @param {Object} config The config that is to be used for the request
  12. *
  13. * @returns {void}
  14. */
  15. function throwIfCancellationRequested(config) {
  16. if (config.cancelToken) {
  17. config.cancelToken.throwIfRequested();
  18. }
  19. if (config.signal && config.signal.aborted) {
  20. throw new CanceledError(null, config);
  21. }
  22. }
  23. /**
  24. * Dispatch a request to the server using the configured adapter.
  25. *
  26. * @param {object} config The config that is to be used for the request
  27. *
  28. * @returns {Promise} The Promise to be fulfilled
  29. */
  30. export default function dispatchRequest(config) {
  31. throwIfCancellationRequested(config);
  32. config.headers = AxiosHeaders.from(config.headers);
  33. // Transform request data
  34. config.data = transformData.call(config, config.transformRequest);
  35. if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
  36. config.headers.setContentType('application/x-www-form-urlencoded', false);
  37. }
  38. const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
  39. return adapter(config).then(
  40. function onAdapterResolution(response) {
  41. throwIfCancellationRequested(config);
  42. // Expose the current response on config so that transformResponse can
  43. // attach it to any AxiosError it throws (e.g. on JSON parse failure).
  44. // We clean it up afterwards to avoid polluting the config object.
  45. config.response = response;
  46. try {
  47. response.data = transformData.call(config, config.transformResponse, response);
  48. } finally {
  49. delete config.response;
  50. }
  51. response.headers = AxiosHeaders.from(response.headers);
  52. return response;
  53. },
  54. function onAdapterRejection(reason) {
  55. if (!isCancel(reason)) {
  56. throwIfCancellationRequested(config);
  57. // Transform response data
  58. if (reason && reason.response) {
  59. config.response = reason.response;
  60. try {
  61. reason.response.data = transformData.call(
  62. config,
  63. config.transformResponse,
  64. reason.response
  65. );
  66. } finally {
  67. delete config.response;
  68. }
  69. reason.response.headers = AxiosHeaders.from(reason.response.headers);
  70. }
  71. }
  72. return Promise.reject(reason);
  73. }
  74. );
  75. }