axios.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. /* !
  2. * uni-axios-ts
  3. * library v0.0.4
  4. * github address https://gitee.com/codeweb/uni-axios-ts.git
  5. *
  6. * (c) 2019.12 xtshadow
  7. */
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global = global || self, global.axios = factory());
  12. }(this, (function () { 'use strict';
  13. /**
  14. * 请求Method类型
  15. */
  16. var Method;
  17. (function (Method) {
  18. Method["GET"] = "GET";
  19. Method["POST"] = "POST";
  20. Method["PUT"] = "PUT";
  21. Method["HEAD"] = "HEAD";
  22. Method["DELETE"] = "DELETE";
  23. Method["TRACE"] = "TRACE";
  24. Method["CONNECT"] = "CONNECT";
  25. Method["OPTIONS"] = "OPTIONS";
  26. })(Method || (Method = {}));
  27. /**
  28. * 响应的数据类型
  29. */
  30. var HttpResponseType;
  31. (function (HttpResponseType) {
  32. HttpResponseType["TEXT"] = "text";
  33. HttpResponseType["ARRAYBUFFER"] = "arraybuffer";
  34. })(HttpResponseType || (HttpResponseType = {}));
  35. var AxiosError =
  36. /*@__PURE__*/
  37. function (Error) {
  38. function AxiosError(message, statusCode, config, request, response) {
  39. Error.call(this, message);
  40. this.config = config;
  41. this.statusCode = statusCode;
  42. this.request = request;
  43. this.response = response;
  44. Object.setPrototypeOf(this, AxiosError.prototype);
  45. }
  46. if (Error) AxiosError.__proto__ = Error;
  47. AxiosError.prototype = Object.create(Error && Error.prototype);
  48. AxiosError.prototype.constructor = AxiosError;
  49. return AxiosError;
  50. }(Error);
  51. function createError(message, statusCode, config, request, response) {
  52. var error = new AxiosError(message, statusCode, config, request, response);
  53. return error;
  54. }
  55. /**
  56. * 执行请求,调用微信Request方法
  57. * @param config
  58. */
  59. function wxRequest(config) {
  60. var url = config.url;
  61. var method = config.method;
  62. if (method === void 0) method = Method.GET;
  63. var data = config.data;
  64. if (data === void 0) data = {};
  65. var header = config.header;
  66. if (header === void 0) header = {};
  67. var responseType = config.responseType;
  68. if (responseType === void 0) responseType = HttpResponseType.TEXT;
  69. var cancelToken = config.cancelToken;
  70. var validateStatus = config.validateStatus;
  71. return new Promise(function (resolve, reject) {
  72. // @ts-ignore
  73. var requestTask = uni.request({
  74. url: url,
  75. header: header,
  76. method: method,
  77. data: data,
  78. responseType: responseType,
  79. success: function success(res) {
  80. var response = {
  81. data: res.data,
  82. statusCode: res.statusCode,
  83. header: res.header
  84. };
  85. if (!validateStatus || validateStatus(res.statusCode)) {
  86. resolve(response);
  87. } else {
  88. reject(createError("Request failed with status code " + response.statusCode, response.statusCode, config, requestTask, response));
  89. }
  90. },
  91. fail: function fail(error) {
  92. reject(createError("Net Error", 1001, config, requestTask));
  93. }
  94. }); // 请求取消
  95. if (cancelToken) {
  96. cancelToken.promise.then(function (reason) {
  97. requestTask.abort();
  98. reject(reason);
  99. });
  100. }
  101. });
  102. }
  103. function _typeof(obj) {
  104. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  105. _typeof = function (obj) {
  106. return typeof obj;
  107. };
  108. } else {
  109. _typeof = function (obj) {
  110. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  111. };
  112. }
  113. return _typeof(obj);
  114. }
  115. var toString = Object.prototype.toString;
  116. /**
  117. * Determine if a value is an Array
  118. *
  119. * @param {Object} val The value to test
  120. * @returns {boolean} True if value is an Array, otherwise false
  121. */
  122. function isArray(val) {
  123. return toString.call(val) === '[object Array]';
  124. }
  125. /**
  126. * 确定值是否为对象
  127. *
  128. * @param {Object} val 要测试的值
  129. * @returns {boolean} 如果值是对象,则为true;否则为false
  130. */
  131. function isObject(val) {
  132. return val !== null && _typeof(val) === 'object';
  133. }
  134. /**
  135. * 迭代Array或为每个项目调用函数的对象。
  136. *
  137. * 如果`obj`为数组回调将被调用传递。
  138. * 每项的值、索引和完整数组。
  139. *
  140. * 如果`obj`是一个对象回调将被调用传递。
  141. * 每个属性的值、键和Complete对象。
  142. *
  143. * @param{object|Array} obj要迭代的对象。
  144. * @param{function} fn要为每个项调用的回调。
  145. */
  146. function forEach(obj, fn) {
  147. if (obj !== null && typeof obj !== 'undefined') {
  148. // Force an array if not already something iterable
  149. // 数组也属于对象
  150. if (_typeof(obj) !== 'object') {
  151. /*eslint no-param-reassign:0*/
  152. obj = [obj];
  153. }
  154. if (isArray(obj)) {
  155. // Iterate over array values
  156. for (var i = 0, l = obj.length; i < l; i++) {
  157. fn.call(null, obj[i], i, obj);
  158. }
  159. } else {
  160. // Iterate over object keys
  161. Object.getOwnPropertyNames(obj).forEach(function (key) {
  162. if (Object.prototype.hasOwnProperty.call(obj, key) && key !== 'constructor') {
  163. fn.call(null, obj[key], key, obj);
  164. }
  165. }); // for (let key in obj) {
  166. // console.log(`forin key:${key}`);
  167. // if (Object.prototype.hasOwnProperty.call(obj, key)) {
  168. // console.log(`callback:${key}`)
  169. // fn.call(null, obj[key], key, obj);
  170. // }
  171. // }
  172. }
  173. }
  174. }
  175. /**
  176. * 通过可变地向`对象A`添加`对象B`的属性来扩展`对象A`
  177. *
  178. * @param {Object} a 要扩展的对象
  179. * @param {Object} b 要从中复制属性的对象
  180. * @param {Object} thisArg 要将函数绑定到的对象
  181. * @return {Object} 对象a的结果
  182. */
  183. function extend(a, b, thisArg) {
  184. forEach(b, function assignValue(val, key) {
  185. if (thisArg && typeof val === 'function') {
  186. // a[key] = bind(val, thisArg);
  187. a[key] = val.bind(thisArg);
  188. } else {
  189. a[key] = val;
  190. }
  191. });
  192. return a;
  193. }
  194. /**
  195. * 函数等于merge,差值为无引用
  196. * 保留为原始对象
  197. * @see merge
  198. * @param {Object} obj1 Object to merge
  199. * @returns {Object} Result of all merge properties
  200. */
  201. function deepMerge() {
  202. var objs = [],
  203. len = arguments.length;
  204. while (len--) {
  205. objs[len] = arguments[len];
  206. }
  207. var result = Object.create(null);
  208. function assignValue(val, key) {
  209. if (isObject(result[key] && isObject(val))) {
  210. result[key] = deepMerge(result[key], val);
  211. } else if (isObject(val)) {
  212. result[key] = deepMerge({}, val);
  213. } else {
  214. result[key] = val;
  215. }
  216. }
  217. for (var i = 0; i < objs.length; i++) {
  218. var obj = objs[i];
  219. for (var key in obj) {
  220. assignValue(obj[key], key);
  221. }
  222. }
  223. return result;
  224. }
  225. /**
  226. * 标准格式化请求头
  227. * @param headers 请求头对象
  228. * @param normalizeName 标准名称
  229. */
  230. function normalizeHeaderName(header, normalizeName) {
  231. Object.keys(header).forEach(function (name) {
  232. if (name !== normalizeName && name.toUpperCase() === normalizeName.toUpperCase()) {
  233. header[normalizeName] = header[name];
  234. delete header[name];
  235. }
  236. });
  237. }
  238. /**
  239. * 格式化加工 Header请求头
  240. * @param headers
  241. */
  242. function processHeaders(header) {
  243. normalizeHeaderName(header, 'Content-Type');
  244. normalizeHeaderName(header, 'appId');
  245. normalizeHeaderName(header, 'sessionId');
  246. return header;
  247. }
  248. /**
  249. * 请求头扁平化
  250. *
  251. * @param headers
  252. * @param method
  253. */
  254. function flattenHeaders(headers, method) {
  255. if (!headers) {
  256. return headers;
  257. }
  258. headers = deepMerge(headers.common || {}, headers[method.toLocaleLowerCase()] || {}, headers);
  259. var methodsToDelete = ['delete', 'get', 'head', 'options', 'post', 'put', 'patch', 'common'];
  260. methodsToDelete.forEach(function (method) {
  261. delete headers[method];
  262. });
  263. return headers;
  264. }
  265. /**
  266. * 组合URL
  267. * @param baseURL
  268. * @param relativeUrl
  269. */
  270. function combineURL(baseURL, relativeURL) {
  271. return relativeURL ? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
  272. }
  273. /**
  274. * 判断`URL`是否是绝对路径
  275. * @param url
  276. * @return {boolean}
  277. */
  278. function isAbsoluteURL(url) {
  279. // 如果URL以“<scheme>://”或“//”(协议相对URL)开头,则该URL被视为绝对值。
  280. // RFC 3986将方案名称定义为以字母开头的字符序列,
  281. // 后跟字母,数字,加号,句点或连字符的任意组合。
  282. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
  283. }
  284. /**
  285. * 处理请求头
  286. * @param config
  287. */
  288. function transformHeaders(config) {
  289. var header = config.header;
  290. if (header === void 0) header = {};
  291. var method = config.method;
  292. if (method === void 0) method = Method.GET;
  293. header = processHeaders(header);
  294. return flattenHeaders(header, method);
  295. }
  296. /**
  297. * 处理请求地址 URL
  298. * @param config
  299. */
  300. function transformUrl(config) {
  301. var url = config.url;
  302. if (url === void 0) url = '';
  303. var baseURL = config.baseURL;
  304. if (baseURL === void 0) baseURL = '';
  305. if (baseURL && !isAbsoluteURL(url)) {
  306. url = combineURL(baseURL, url);
  307. }
  308. return url;
  309. }
  310. /**
  311. * 抛出异常
  312. *
  313. * 如果当前`cancelToken`已经取消请求,则抛出异常
  314. * @param config
  315. */
  316. function throwIfCancellationRequested(config) {
  317. if (config.cancelToken) {
  318. config.cancelToken.throwIfRequested();
  319. }
  320. }
  321. /**
  322. * 预处理配置文件
  323. * @param config 配置文件
  324. */
  325. function processConfig(config) {
  326. config.header = transformHeaders(config);
  327. config.url = transformUrl(config);
  328. }
  329. /**
  330. * 执行请求
  331. * @param config 配置文件
  332. */
  333. function dispatchRequest(config) {
  334. throwIfCancellationRequested(config);
  335. processConfig(config);
  336. return wxRequest(config);
  337. }
  338. var InterceptorManager = function InterceptorManager() {
  339. this.handlers = [];
  340. };
  341. InterceptorManager.prototype.use = function use(resolved, rejected) {
  342. this.handlers.push({
  343. resolved: resolved,
  344. rejected: rejected
  345. });
  346. return this.handlers.length - 1;
  347. };
  348. InterceptorManager.prototype.eject = function eject(id) {
  349. if (this.handlers[id]) {
  350. this.handlers[id] = null;
  351. }
  352. };
  353. InterceptorManager.prototype.forEach = function forEach(fn) {
  354. this.handlers.forEach(function (interceptor) {
  355. if (interceptor !== null) {
  356. fn(interceptor);
  357. }
  358. });
  359. };
  360. function mergeConfig(defaultConfig, userConfig) {
  361. var config = Object.create(null); // 创建空对象,作为最终的合并结果
  362. // 1.常规属性,如果用户配置了就用用户配置的,如果用户没配置,则用默认配置的;
  363. var defaultToUserConfig = ["baseURL", "transformRequest", "transformResponse", "paramsSerializer", "timeout", "withCredentials", "adapter", "responseType", "xsrfCookieName", "xsrfHeaderName", "onUploadProgress", "onDownloadProgress", "maxContentLength", "validateStatus", "maxRedirects", "httpAgent", "httpsAgent", "cancelToken", "socketPath"];
  364. defaultToUserConfig.forEach(function (prop) {
  365. userConfig = userConfig || {}; // 如果用户配置里有
  366. if (typeof userConfig[prop] !== "undefined") {
  367. // 则用用户配置里的
  368. config[prop] = userConfig[prop]; // 如果用户配置里没有,默认配置里有
  369. } else if (typeof defaultConfig[prop] !== "undefined") {
  370. // 则用默认配置里的
  371. config[prop] = defaultConfig[prop];
  372. }
  373. }); // 2.只接受用户配置,不管默认配置对象里面有没有,我们只取用户配置的;
  374. var valueFromUserConfig = ["url", "method", "params", "data"];
  375. valueFromUserConfig.forEach(function (prop) {
  376. userConfig = userConfig || {};
  377. if (typeof userConfig[prop] !== 'undefined') {
  378. config[prop] = userConfig[prop];
  379. }
  380. }); // 3.复杂对象深度合并
  381. var mergeDeepProperties = ["header", "auth", "proxy"];
  382. mergeDeepProperties.forEach(function (prop) {
  383. userConfig = userConfig || {};
  384. if (isObject(userConfig[prop])) {
  385. config[prop] = deepMerge(defaultConfig[prop], userConfig[prop]);
  386. } else if (typeof userConfig[prop] !== 'undefined') {
  387. config[prop] = userConfig[prop];
  388. } else if (isObject(defaultConfig[prop])) {
  389. config[prop] = deepMerge(defaultConfig[prop]);
  390. } else if (typeof defaultConfig[prop] !== 'undefined') {
  391. config[prop] = defaultConfig[prop];
  392. }
  393. });
  394. return config;
  395. }
  396. var Axios = function Axios(defaultConfig) {
  397. this.defaults = defaultConfig;
  398. this.interceptors = {
  399. request: new InterceptorManager(),
  400. response: new InterceptorManager()
  401. };
  402. };
  403. Axios.prototype.request = function request(config) {
  404. // 合并参数
  405. config = mergeConfig(this.defaults, config); // 拦截器
  406. var promise = Promise.resolve(config);
  407. var chain = [{
  408. resolved: dispatchRequest,
  409. rejected: undefined
  410. }]; // let chain:AxiosInterceptor<any>[] = [
  411. // {
  412. // resolved: dispatchRequest,
  413. // rejected: undefined
  414. // }
  415. // ];
  416. this.interceptors.request.forEach(function (interceptor) {
  417. chain.unshift(interceptor);
  418. });
  419. this.interceptors.response.forEach(function (interceptor) {
  420. chain.push(interceptor);
  421. });
  422. while (chain.length > 0) {
  423. var ref = chain.shift();
  424. var resolved = ref.resolved;
  425. var rejected = ref.rejected;
  426. promise = promise.then(resolved, rejected);
  427. }
  428. return promise; // return dispatchRequest(config);
  429. };
  430. Axios.prototype.get = function get(url, config) {
  431. return this._requestMethodWithoutData(Method.GET, url, config);
  432. };
  433. Axios.prototype.post = function post(url, data, config) {
  434. return this._requestMethodWithData(Method.POST, url, data, config);
  435. };
  436. Axios.prototype.put = function put(url, data, config) {
  437. return this._requestMethodWithData(Method.PUT, url, data, config);
  438. };
  439. Axios.prototype["delete"] = function delete$1(url, config) {
  440. return this._requestMethodWithoutData(Method.DELETE, url, config);
  441. };
  442. Axios.prototype.connect = function connect(url, config) {
  443. return this._requestMethodWithoutData(Method.CONNECT, url, config);
  444. };
  445. Axios.prototype.head = function head(url, config) {
  446. return this._requestMethodWithoutData(Method.HEAD, url, config);
  447. };
  448. Axios.prototype.options = function options(url, config) {
  449. return this._requestMethodWithoutData(Method.OPTIONS, url, config);
  450. };
  451. Axios.prototype.trace = function trace(url, config) {
  452. return this._requestMethodWithoutData(Method.TRACE, url, config);
  453. };
  454. Axios.prototype._requestMethodWithData = function _requestMethodWithData(method, url, data, config) {
  455. return this.request(Object.assign(config || {}, {
  456. method: method,
  457. url: url,
  458. data: data
  459. }));
  460. };
  461. Axios.prototype._requestMethodWithoutData = function _requestMethodWithoutData(method, url, config) {
  462. return this.request(Object.assign(config || {}, {
  463. method: method,
  464. url: url
  465. }));
  466. };
  467. /**
  468. * 根据传入的请求配置对象返回一个请求的`URL`
  469. * @param config 请求配置
  470. * @returns {string} 请求`URL`
  471. */
  472. Axios.prototype.getUri = function getUri(config) {
  473. config = mergeConfig(this.defaults, config);
  474. return transformUrl(config);
  475. };
  476. /**
  477. * 默认配置
  478. */
  479. var defaults = {
  480. baseURL: '',
  481. header: {},
  482. method: Method.GET,
  483. responseType: HttpResponseType.TEXT,
  484. validateStatus: function validateStatus(status) {
  485. return status >= 200 && status < 300;
  486. }
  487. };
  488. var Cancel = function Cancel(message) {
  489. if (message === void 0) message = '';
  490. this.message = message;
  491. };
  492. var CancelToken = function CancelToken(executor) {
  493. var this$1 = this;
  494. var resolvePromise;
  495. this.promise = new Promise(function (resolve) {
  496. resolvePromise = resolve;
  497. }); // executor 括号内为 一个回调函数作为参数,该函数接收一个string类型的取消原因作为参数
  498. // 调用该回调函数时,会修改 Promise状态为 resolve
  499. executor(function (message) {
  500. if (this$1.reason) {
  501. return;
  502. }
  503. this$1.reason = new Cancel(message);
  504. resolvePromise(this$1.reason); // 修改 Promise状态为 resolve
  505. });
  506. };
  507. CancelToken.source = function source() {
  508. var cancel;
  509. var token = new CancelToken(function (fn) {
  510. cancel = fn;
  511. });
  512. return {
  513. cancel: cancel,
  514. token: token
  515. };
  516. };
  517. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  518. if (this.reason) {
  519. throw this.reason;
  520. }
  521. };
  522. function isCancel(val) {
  523. return val instanceof Cancel;
  524. }
  525. function getAxios(config) {
  526. var context = new Axios(config); // Axios 实例,用于给 axios继承自身属性
  527. var axios = Axios.prototype.request.bind(context); // 复制原型方法,并绑定函数`this` Copy axios.prototype to instance
  528. extend(axios, Axios.prototype, context); // 复制实例属性 Copy context to instance
  529. extend(axios, context);
  530. return axios;
  531. }
  532. var axios = getAxios(defaults);
  533. axios.create = function create(config) {
  534. return getAxios(mergeConfig(defaults, config));
  535. };
  536. axios.CancelToken = CancelToken;
  537. axios.Cancel = Cancel;
  538. axios.isCancel = isCancel;
  539. axios.all = function (promises) {
  540. return Promise.all(promises);
  541. };
  542. axios.spread = function (callback) {
  543. return function wrap(arr) {
  544. return callback.apply(null, arr);
  545. };
  546. };
  547. return axios;
  548. })));