Axios.js 2.1 KB

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