dispatchRequest.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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(
  35. config,
  36. config.transformRequest
  37. );
  38. if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
  39. config.headers.setContentType('application/x-www-form-urlencoded', false);
  40. }
  41. const adapter = adapters.getAdapter(config.adapter || defaults.adapter);
  42. return adapter(config).then(function onAdapterResolution(response) {
  43. throwIfCancellationRequested(config);
  44. // Transform response data
  45. response.data = transformData.call(
  46. config,
  47. config.transformResponse,
  48. response
  49. );
  50. response.headers = AxiosHeaders.from(response.headers);
  51. return response;
  52. }, function onAdapterRejection(reason) {
  53. if (!isCancel(reason)) {
  54. throwIfCancellationRequested(config);
  55. // Transform response data
  56. if (reason && reason.response) {
  57. reason.response.data = transformData.call(
  58. config,
  59. config.transformResponse,
  60. reason.response
  61. );
  62. reason.response.headers = AxiosHeaders.from(reason.response.headers);
  63. }
  64. }
  65. return Promise.reject(reason);
  66. });
  67. }