Axios.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. var defaults = require('./../defaults');
  3. var utils = require('./../utils');
  4. var InterceptorManager = require('./InterceptorManager');
  5. var dispatchRequest = require('./dispatchRequest');
  6. var isAbsoluteURL = require('./../helpers/isAbsoluteURL');
  7. var combineURLs = require('./../helpers/combineURLs');
  8. /**
  9. * Create a new instance of Axios
  10. *
  11. * @param {Object} instanceConfig The default config for the instance
  12. */
  13. function Axios(instanceConfig) {
  14. this.defaults = instanceConfig;
  15. this.interceptors = {
  16. request: new InterceptorManager(),
  17. response: new InterceptorManager()
  18. };
  19. }
  20. /**
  21. * Dispatch a request
  22. *
  23. * @param {Object} config The config specific for this request (merged with this.defaults)
  24. */
  25. Axios.prototype.request = function request(config) {
  26. /*eslint no-param-reassign:0*/
  27. // Allow for axios('example/url'[, config]) a la fetch API
  28. if (typeof config === 'string') {
  29. config = utils.merge({
  30. url: arguments[0]
  31. }, arguments[1]);
  32. }
  33. config = utils.merge(defaults, this.defaults, { method: 'get' }, config);
  34. // Support baseURL config
  35. if (config.baseURL && !isAbsoluteURL(config.url)) {
  36. config.url = combineURLs(config.baseURL, config.url);
  37. }
  38. // Hook up interceptors middleware
  39. var chain = [dispatchRequest, undefined];
  40. var promise = Promise.resolve(config);
  41. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  42. chain.unshift(interceptor.fulfilled, interceptor.rejected);
  43. });
  44. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  45. chain.push(interceptor.fulfilled, interceptor.rejected);
  46. });
  47. while (chain.length) {
  48. promise = promise.then(chain.shift(), chain.shift());
  49. }
  50. return promise;
  51. };
  52. // Provide aliases for supported request methods
  53. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  54. /*eslint func-names:0*/
  55. Axios.prototype[method] = function(url, config) {
  56. return this.request(utils.merge(config || {}, {
  57. method: method,
  58. url: url
  59. }));
  60. };
  61. });
  62. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  63. /*eslint func-names:0*/
  64. Axios.prototype[method] = function(url, data, config) {
  65. return this.request(utils.merge(config || {}, {
  66. method: method,
  67. url: url,
  68. data: data
  69. }));
  70. };
  71. });
  72. module.exports = Axios;