dispatchRequest.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. // Transform response data
  43. response.data = transformData.call(config, config.transformResponse, response);
  44. response.headers = AxiosHeaders.from(response.headers);
  45. return response;
  46. },
  47. function onAdapterRejection(reason) {
  48. if (!isCancel(reason)) {
  49. throwIfCancellationRequested(config);
  50. // Transform response data
  51. if (reason && reason.response) {
  52. reason.response.data = transformData.call(
  53. config,
  54. config.transformResponse,
  55. reason.response
  56. );
  57. reason.response.headers = AxiosHeaders.from(reason.response.headers);
  58. }
  59. }
  60. return Promise.reject(reason);
  61. }
  62. );
  63. }