Http.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import InterceptorManager from '@/utils/Http/InterceptorManager'
  2. import dispatchRequest from '@/utils/Http/dispatchRequest';
  3. import _ from '@/assets/scripts/lodash';
  4. function Http(instanceConfig) {
  5. this.defaults = instanceConfig;
  6. this.interceptors = {
  7. request: new InterceptorManager(),
  8. response: new InterceptorManager()
  9. };
  10. }
  11. Http.prototype.request = function (config) {
  12. if (typeof config === 'string') {
  13. config = arguments[1] || {};
  14. config.url = arguments[0];
  15. } else {
  16. config = config || {};
  17. }
  18. config = Object.assign(this.defaults, config);
  19. config.method = config.method ? config.method.toUpperCase() : 'GET';
  20. let promise = Promise.resolve(config);
  21. const chain = [dispatchRequest, undefined];
  22. this.interceptors.request.forEach(interceptor => {
  23. chain.unshift(interceptor.resolve, interceptor.reject);
  24. });
  25. this.interceptors.response.forEach(interceptor => {
  26. chain.push(interceptor.resolve, interceptor.reject);
  27. });
  28. while(chain.length) {
  29. promise = promise.then(chain.shift(), chain.shift());
  30. }
  31. return promise;
  32. }
  33. _.forEach(['get', 'delete'], (method) => {
  34. Http.prototype[method] = function (url, config) {
  35. const params = config && config.params;
  36. if (params) {
  37. config.data = params;
  38. }
  39. return this.request(Object.assign(config || {}, {
  40. method: method.toUpperCase(),
  41. url,
  42. header:{
  43. 'token':uni.getStorageSync("token")
  44. },
  45. dataType: 'json'
  46. }));
  47. }
  48. });
  49. _.forEach(['post', 'put'], (method) => {
  50. Http.prototype[method] = function (url, data, config) {
  51. return this.request(Object.assign(config || {}, {
  52. method: method.toUpperCase(),
  53. url,
  54. data,
  55. header:{
  56. 'token':uni.getStorageSync("token")
  57. },
  58. dataType: 'json'
  59. }));
  60. }
  61. });
  62. export default Http;