index.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. /*!
  2. * axios-miniprogram-adapter 0.3.4 (https://github.com/bigMeow/axios-miniprogram-adapter)
  3. * API https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/doc/api.md
  4. * Copyright 2018-2022 bigMeow. All Rights Reserved
  5. * Licensed under MIT (https://github.com/bigMeow/axios-miniprogram-adapter/blob/master/LICENSE)
  6. */
  7. 'use strict';
  8. var bind = function bind(fn, thisArg) {
  9. return function wrap() {
  10. var args = new Array(arguments.length);
  11. for (var i = 0; i < args.length; i++) {
  12. args[i] = arguments[i];
  13. }
  14. return fn.apply(thisArg, args);
  15. };
  16. };
  17. /*global toString:true*/
  18. // utils is a library of generic helper functions non-specific to axios
  19. var toString = Object.prototype.toString;
  20. /**
  21. * Determine if a value is an Array
  22. *
  23. * @param {Object} val The value to test
  24. * @returns {boolean} True if value is an Array, otherwise false
  25. */
  26. function isArray(val) {
  27. return toString.call(val) === '[object Array]';
  28. }
  29. /**
  30. * Determine if a value is undefined
  31. *
  32. * @param {Object} val The value to test
  33. * @returns {boolean} True if the value is undefined, otherwise false
  34. */
  35. function isUndefined(val) {
  36. return typeof val === 'undefined';
  37. }
  38. /**
  39. * Determine if a value is a Buffer
  40. *
  41. * @param {Object} val The value to test
  42. * @returns {boolean} True if value is a Buffer, otherwise false
  43. */
  44. function isBuffer(val) {
  45. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
  46. && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
  47. }
  48. /**
  49. * Determine if a value is an ArrayBuffer
  50. *
  51. * @param {Object} val The value to test
  52. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  53. */
  54. function isArrayBuffer(val) {
  55. return toString.call(val) === '[object ArrayBuffer]';
  56. }
  57. /**
  58. * Determine if a value is a FormData
  59. *
  60. * @param {Object} val The value to test
  61. * @returns {boolean} True if value is an FormData, otherwise false
  62. */
  63. function isFormData(val) {
  64. return (typeof FormData !== 'undefined') && (val instanceof FormData);
  65. }
  66. /**
  67. * Determine if a value is a view on an ArrayBuffer
  68. *
  69. * @param {Object} val The value to test
  70. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  71. */
  72. function isArrayBufferView(val) {
  73. var result;
  74. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  75. result = ArrayBuffer.isView(val);
  76. } else {
  77. result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
  78. }
  79. return result;
  80. }
  81. /**
  82. * Determine if a value is a String
  83. *
  84. * @param {Object} val The value to test
  85. * @returns {boolean} True if value is a String, otherwise false
  86. */
  87. function isString(val) {
  88. return typeof val === 'string';
  89. }
  90. /**
  91. * Determine if a value is a Number
  92. *
  93. * @param {Object} val The value to test
  94. * @returns {boolean} True if value is a Number, otherwise false
  95. */
  96. function isNumber(val) {
  97. return typeof val === 'number';
  98. }
  99. /**
  100. * Determine if a value is an Object
  101. *
  102. * @param {Object} val The value to test
  103. * @returns {boolean} True if value is an Object, otherwise false
  104. */
  105. function isObject(val) {
  106. return val !== null && typeof val === 'object';
  107. }
  108. /**
  109. * Determine if a value is a Date
  110. *
  111. * @param {Object} val The value to test
  112. * @returns {boolean} True if value is a Date, otherwise false
  113. */
  114. function isDate(val) {
  115. return toString.call(val) === '[object Date]';
  116. }
  117. /**
  118. * Determine if a value is a File
  119. *
  120. * @param {Object} val The value to test
  121. * @returns {boolean} True if value is a File, otherwise false
  122. */
  123. function isFile(val) {
  124. return toString.call(val) === '[object File]';
  125. }
  126. /**
  127. * Determine if a value is a Blob
  128. *
  129. * @param {Object} val The value to test
  130. * @returns {boolean} True if value is a Blob, otherwise false
  131. */
  132. function isBlob(val) {
  133. return toString.call(val) === '[object Blob]';
  134. }
  135. /**
  136. * Determine if a value is a Function
  137. *
  138. * @param {Object} val The value to test
  139. * @returns {boolean} True if value is a Function, otherwise false
  140. */
  141. function isFunction(val) {
  142. return toString.call(val) === '[object Function]';
  143. }
  144. /**
  145. * Determine if a value is a Stream
  146. *
  147. * @param {Object} val The value to test
  148. * @returns {boolean} True if value is a Stream, otherwise false
  149. */
  150. function isStream(val) {
  151. return isObject(val) && isFunction(val.pipe);
  152. }
  153. /**
  154. * Determine if a value is a URLSearchParams object
  155. *
  156. * @param {Object} val The value to test
  157. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  158. */
  159. function isURLSearchParams(val) {
  160. return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
  161. }
  162. /**
  163. * Trim excess whitespace off the beginning and end of a string
  164. *
  165. * @param {String} str The String to trim
  166. * @returns {String} The String freed of excess whitespace
  167. */
  168. function trim(str) {
  169. return str.replace(/^\s*/, '').replace(/\s*$/, '');
  170. }
  171. /**
  172. * Determine if we're running in a standard browser environment
  173. *
  174. * This allows axios to run in a web worker, and react-native.
  175. * Both environments support XMLHttpRequest, but not fully standard globals.
  176. *
  177. * web workers:
  178. * typeof window -> undefined
  179. * typeof document -> undefined
  180. *
  181. * react-native:
  182. * navigator.product -> 'ReactNative'
  183. * nativescript
  184. * navigator.product -> 'NativeScript' or 'NS'
  185. */
  186. function isStandardBrowserEnv() {
  187. if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
  188. navigator.product === 'NativeScript' ||
  189. navigator.product === 'NS')) {
  190. return false;
  191. }
  192. return (
  193. typeof window !== 'undefined' &&
  194. typeof document !== 'undefined'
  195. );
  196. }
  197. /**
  198. * Iterate over an Array or an Object invoking a function for each item.
  199. *
  200. * If `obj` is an Array callback will be called passing
  201. * the value, index, and complete array for each item.
  202. *
  203. * If 'obj' is an Object callback will be called passing
  204. * the value, key, and complete object for each property.
  205. *
  206. * @param {Object|Array} obj The object to iterate
  207. * @param {Function} fn The callback to invoke for each item
  208. */
  209. function forEach(obj, fn) {
  210. // Don't bother if no value provided
  211. if (obj === null || typeof obj === 'undefined') {
  212. return;
  213. }
  214. // Force an array if not already something iterable
  215. if (typeof obj !== 'object') {
  216. /*eslint no-param-reassign:0*/
  217. obj = [obj];
  218. }
  219. if (isArray(obj)) {
  220. // Iterate over array values
  221. for (var i = 0, l = obj.length; i < l; i++) {
  222. fn.call(null, obj[i], i, obj);
  223. }
  224. } else {
  225. // Iterate over object keys
  226. for (var key in obj) {
  227. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  228. fn.call(null, obj[key], key, obj);
  229. }
  230. }
  231. }
  232. }
  233. /**
  234. * Accepts varargs expecting each argument to be an object, then
  235. * immutably merges the properties of each object and returns result.
  236. *
  237. * When multiple objects contain the same key the later object in
  238. * the arguments list will take precedence.
  239. *
  240. * Example:
  241. *
  242. * ```js
  243. * var result = merge({foo: 123}, {foo: 456});
  244. * console.log(result.foo); // outputs 456
  245. * ```
  246. *
  247. * @param {Object} obj1 Object to merge
  248. * @returns {Object} Result of all merge properties
  249. */
  250. function merge(/* obj1, obj2, obj3, ... */) {
  251. var result = {};
  252. function assignValue(val, key) {
  253. if (typeof result[key] === 'object' && typeof val === 'object') {
  254. result[key] = merge(result[key], val);
  255. } else {
  256. result[key] = val;
  257. }
  258. }
  259. for (var i = 0, l = arguments.length; i < l; i++) {
  260. forEach(arguments[i], assignValue);
  261. }
  262. return result;
  263. }
  264. /**
  265. * Function equal to merge with the difference being that no reference
  266. * to original objects is kept.
  267. *
  268. * @see merge
  269. * @param {Object} obj1 Object to merge
  270. * @returns {Object} Result of all merge properties
  271. */
  272. function deepMerge(/* obj1, obj2, obj3, ... */) {
  273. var result = {};
  274. function assignValue(val, key) {
  275. if (typeof result[key] === 'object' && typeof val === 'object') {
  276. result[key] = deepMerge(result[key], val);
  277. } else if (typeof val === 'object') {
  278. result[key] = deepMerge({}, val);
  279. } else {
  280. result[key] = val;
  281. }
  282. }
  283. for (var i = 0, l = arguments.length; i < l; i++) {
  284. forEach(arguments[i], assignValue);
  285. }
  286. return result;
  287. }
  288. /**
  289. * Extends object a by mutably adding to it the properties of object b.
  290. *
  291. * @param {Object} a The object to be extended
  292. * @param {Object} b The object to copy properties from
  293. * @param {Object} thisArg The object to bind function to
  294. * @return {Object} The resulting value of object a
  295. */
  296. function extend(a, b, thisArg) {
  297. forEach(b, function assignValue(val, key) {
  298. if (thisArg && typeof val === 'function') {
  299. a[key] = bind(val, thisArg);
  300. } else {
  301. a[key] = val;
  302. }
  303. });
  304. return a;
  305. }
  306. var utils = {
  307. isArray: isArray,
  308. isArrayBuffer: isArrayBuffer,
  309. isBuffer: isBuffer,
  310. isFormData: isFormData,
  311. isArrayBufferView: isArrayBufferView,
  312. isString: isString,
  313. isNumber: isNumber,
  314. isObject: isObject,
  315. isUndefined: isUndefined,
  316. isDate: isDate,
  317. isFile: isFile,
  318. isBlob: isBlob,
  319. isFunction: isFunction,
  320. isStream: isStream,
  321. isURLSearchParams: isURLSearchParams,
  322. isStandardBrowserEnv: isStandardBrowserEnv,
  323. forEach: forEach,
  324. merge: merge,
  325. deepMerge: deepMerge,
  326. extend: extend,
  327. trim: trim
  328. };
  329. /**
  330. * Update an Error with the specified config, error code, and response.
  331. *
  332. * @param {Error} error The error to update.
  333. * @param {Object} config The config.
  334. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  335. * @param {Object} [request] The request.
  336. * @param {Object} [response] The response.
  337. * @returns {Error} The error.
  338. */
  339. var enhanceError = function enhanceError(error, config, code, request, response) {
  340. error.config = config;
  341. if (code) {
  342. error.code = code;
  343. }
  344. error.request = request;
  345. error.response = response;
  346. error.isAxiosError = true;
  347. error.toJSON = function() {
  348. return {
  349. // Standard
  350. message: this.message,
  351. name: this.name,
  352. // Microsoft
  353. description: this.description,
  354. number: this.number,
  355. // Mozilla
  356. fileName: this.fileName,
  357. lineNumber: this.lineNumber,
  358. columnNumber: this.columnNumber,
  359. stack: this.stack,
  360. // Axios
  361. config: this.config,
  362. code: this.code
  363. };
  364. };
  365. return error;
  366. };
  367. /**
  368. * Create an Error with the specified message, config, error code, request and response.
  369. *
  370. * @param {string} message The error message.
  371. * @param {Object} config The config.
  372. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  373. * @param {Object} [request] The request.
  374. * @param {Object} [response] The response.
  375. * @returns {Error} The created error.
  376. */
  377. var createError = function createError(message, config, code, request, response) {
  378. var error = new Error(message);
  379. return enhanceError(error, config, code, request, response);
  380. };
  381. /**
  382. * Resolve or reject a Promise based on response status.
  383. *
  384. * @param {Function} resolve A function that resolves the promise.
  385. * @param {Function} reject A function that rejects the promise.
  386. * @param {object} response The response.
  387. */
  388. var settle = function settle(resolve, reject, response) {
  389. var validateStatus = response.config.validateStatus;
  390. if (!validateStatus || validateStatus(response.status)) {
  391. resolve(response);
  392. } else {
  393. reject(createError(
  394. 'Request failed with status code ' + response.status,
  395. response.config,
  396. null,
  397. response.request,
  398. response
  399. ));
  400. }
  401. };
  402. function encode(val) {
  403. return encodeURIComponent(val).
  404. replace(/%40/gi, '@').
  405. replace(/%3A/gi, ':').
  406. replace(/%24/g, '$').
  407. replace(/%2C/gi, ',').
  408. replace(/%20/g, '+').
  409. replace(/%5B/gi, '[').
  410. replace(/%5D/gi, ']');
  411. }
  412. /**
  413. * Build a URL by appending params to the end
  414. *
  415. * @param {string} url The base of the url (e.g., http://www.google.com)
  416. * @param {object} [params] The params to be appended
  417. * @returns {string} The formatted url
  418. */
  419. var buildURL = function buildURL(url, params, paramsSerializer) {
  420. /*eslint no-param-reassign:0*/
  421. if (!params) {
  422. return url;
  423. }
  424. var serializedParams;
  425. if (paramsSerializer) {
  426. serializedParams = paramsSerializer(params);
  427. } else if (utils.isURLSearchParams(params)) {
  428. serializedParams = params.toString();
  429. } else {
  430. var parts = [];
  431. utils.forEach(params, function serialize(val, key) {
  432. if (val === null || typeof val === 'undefined') {
  433. return;
  434. }
  435. if (utils.isArray(val)) {
  436. key = key + '[]';
  437. } else {
  438. val = [val];
  439. }
  440. utils.forEach(val, function parseValue(v) {
  441. if (utils.isDate(v)) {
  442. v = v.toISOString();
  443. } else if (utils.isObject(v)) {
  444. v = JSON.stringify(v);
  445. }
  446. parts.push(encode(key) + '=' + encode(v));
  447. });
  448. });
  449. serializedParams = parts.join('&');
  450. }
  451. if (serializedParams) {
  452. var hashmarkIndex = url.indexOf('#');
  453. if (hashmarkIndex !== -1) {
  454. url = url.slice(0, hashmarkIndex);
  455. }
  456. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  457. }
  458. return url;
  459. };
  460. /**
  461. * Determines whether the specified URL is absolute
  462. *
  463. * @param {string} url The URL to test
  464. * @returns {boolean} True if the specified URL is absolute, otherwise false
  465. */
  466. var isAbsoluteURL = function isAbsoluteURL(url) {
  467. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  468. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  469. // by any combination of letters, digits, plus, period, or hyphen.
  470. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
  471. };
  472. /**
  473. * Creates a new URL by combining the specified URLs
  474. *
  475. * @param {string} baseURL The base URL
  476. * @param {string} relativeURL The relative URL
  477. * @returns {string} The combined URL
  478. */
  479. var combineURLs = function combineURLs(baseURL, relativeURL) {
  480. return relativeURL
  481. ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
  482. : baseURL;
  483. };
  484. /**
  485. * Creates a new URL by combining the baseURL with the requestedURL,
  486. * only when the requestedURL is not already an absolute URL.
  487. * If the requestURL is absolute, this function returns the requestedURL untouched.
  488. *
  489. * @param {string} baseURL The base URL
  490. * @param {string} requestedURL Absolute or relative URL to combine
  491. * @returns {string} The combined full path
  492. */
  493. var buildFullPath = function buildFullPath(baseURL, requestedURL) {
  494. if (baseURL && !isAbsoluteURL(requestedURL)) {
  495. return combineURLs(baseURL, requestedURL);
  496. }
  497. return requestedURL;
  498. };
  499. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  500. // encoder
  501. function encoder(input) {
  502. var str = String(input);
  503. // initialize result and counter
  504. var block;
  505. var charCode;
  506. var idx = 0;
  507. var map = chars;
  508. var output = '';
  509. for (;
  510. // if the next str index does not exist:
  511. // change the mapping table to "="
  512. // check if d has no fractional digits
  513. str.charAt(idx | 0) || (map = '=', idx % 1);
  514. // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
  515. output += map.charAt(63 & block >> 8 - idx % 1 * 8)) {
  516. charCode = str.charCodeAt(idx += 3 / 4);
  517. if (charCode > 0xFF) {
  518. throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
  519. }
  520. block = block << 8 | charCode;
  521. }
  522. return output;
  523. }
  524. var platFormName = "wechat" /* 微信 */;
  525. /**
  526. * 获取各个平台的请求函数
  527. */
  528. function getRequest() {
  529. switch (true) {
  530. case typeof wx === 'object':
  531. platFormName = "wechat" /* 微信 */;
  532. return wx.request.bind(wx);
  533. case typeof swan === 'object':
  534. platFormName = "baidu" /* 百度 */;
  535. return swan.request.bind(swan);
  536. case typeof dd === 'object':
  537. platFormName = "dd" /* 钉钉 */;
  538. // https://open.dingtalk.com/document/orgapp-client/send-network-requests
  539. return dd.httpRequest.bind(dd);
  540. case typeof my === 'object':
  541. /**
  542. * remark:
  543. * 支付宝客户端已不再维护 my.httpRequest,建议使用 my.request。另外,钉钉客户端尚不支持 my.request。若在钉钉客户端开发小程序,则需要使用 my.httpRequest。
  544. * my.httpRequest的请求头默认值为{'content-type': 'application/x-www-form-urlencoded'}。
  545. * my.request的请求头默认值为{'content-type': 'application/json'}。
  546. * 还有个 dd.httpRequest
  547. */
  548. platFormName = "alipay" /* 支付宝 */;
  549. return (my.request || my.httpRequest).bind(my);
  550. default:
  551. return wx.request.bind(wx);
  552. }
  553. }
  554. /**
  555. * 处理各平台返回的响应数据,抹平差异
  556. * @param mpResponse
  557. * @param config axios处理过的请求配置对象
  558. * @param request 小程序的调用发起请求时,传递给小程序api的实际配置
  559. */
  560. function transformResponse(mpResponse, config, mpRequestOption) {
  561. var headers = mpResponse.header || mpResponse.headers;
  562. var status = mpResponse.statusCode || mpResponse.status;
  563. var statusText = '';
  564. if (status === 200) {
  565. statusText = 'OK';
  566. }
  567. else if (status === 400) {
  568. statusText = 'Bad Request';
  569. }
  570. var response = {
  571. data: mpResponse.data,
  572. status: status,
  573. statusText: statusText,
  574. headers: headers,
  575. config: config,
  576. request: mpRequestOption
  577. };
  578. return response;
  579. }
  580. /**
  581. * 处理各平台返回的错误信息,抹平差异
  582. * @param error 小程序api返回的错误对象
  583. * @param reject 上层的promise reject 函数
  584. * @param config
  585. */
  586. function transformError(error, reject, config) {
  587. switch (platFormName) {
  588. case "wechat" /* 微信 */:
  589. if (error.errMsg.indexOf('request:fail abort') !== -1) {
  590. // Handle request cancellation (as opposed to a manual cancellation)
  591. reject(createError('Request aborted', config, 'ECONNABORTED', ''));
  592. }
  593. else if (error.errMsg.indexOf('timeout') !== -1) {
  594. // timeout
  595. reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', ''));
  596. }
  597. else {
  598. // NetWordError
  599. reject(createError('Network Error', config, null, ''));
  600. }
  601. break;
  602. case "dd" /* 钉钉 */:
  603. case "alipay" /* 支付宝 */:
  604. // https://docs.alipay.com/mini/api/network
  605. if ([14, 19].includes(error.error)) {
  606. reject(createError('Request aborted', config, 'ECONNABORTED', '', error));
  607. }
  608. else if ([13].includes(error.error)) {
  609. // timeout
  610. reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', '', error));
  611. }
  612. else {
  613. // NetWordError
  614. reject(createError('Network Error', config, null, '', error));
  615. }
  616. break;
  617. case "baidu" /* 百度 */:
  618. // TODO error.errCode
  619. reject(createError('Network Error', config, null, ''));
  620. break;
  621. }
  622. }
  623. /**
  624. * 将axios的请求配置,转换成各个平台都支持的请求config
  625. * @param config
  626. */
  627. function transformConfig(config) {
  628. var _a;
  629. if (["alipay" /* 支付宝 */, "dd" /* 钉钉 */].includes(platFormName)) {
  630. config.headers = config.header;
  631. delete config.header;
  632. if ("dd" /* 钉钉 */ === platFormName && config.method !== "GET" && ((_a = config.headers) === null || _a === void 0 ? void 0 : _a['Content-Type']) === 'application/json' && Object.prototype.toString.call(config.data) === '[object Object]') {
  633. // Content-Type为application/json时,data参数只支持json字符串,需要手动调用JSON.stringify进行序列化
  634. config.data = JSON.stringify(config.data);
  635. }
  636. }
  637. return config;
  638. }
  639. var isJSONstr = function (str) {
  640. try {
  641. return typeof str === 'string' && str.length && (str = JSON.parse(str)) && Object.prototype.toString.call(str) === '[object Object]';
  642. }
  643. catch (error) {
  644. return false;
  645. }
  646. };
  647. function mpAdapter(config) {
  648. var request = getRequest();
  649. return new Promise(function (resolve, reject) {
  650. var requestTask;
  651. var requestData = config.data;
  652. var requestHeaders = config.headers;
  653. // baidu miniprogram only support upperCase
  654. var requestMethod = (config.method && config.method.toUpperCase()) || 'GET';
  655. // miniprogram network request config
  656. var mpRequestOption = {
  657. method: requestMethod,
  658. url: buildURL(buildFullPath(config.baseURL, config.url), config.params, config.paramsSerializer),
  659. timeout: config.timeout,
  660. // Listen for success
  661. success: function (mpResponse) {
  662. var response = transformResponse(mpResponse, config, mpRequestOption);
  663. settle(resolve, reject, response);
  664. },
  665. // Handle request Exception
  666. fail: function (error) {
  667. transformError(error, reject, config);
  668. },
  669. complete: function () {
  670. requestTask = undefined;
  671. }
  672. };
  673. // HTTP basic authentication
  674. if (config.auth) {
  675. var _a = [config.auth.username || '', config.auth.password || ''], username = _a[0], password = _a[1];
  676. requestHeaders.Authorization = 'Basic ' + encoder(username + ':' + password);
  677. }
  678. // Add headers to the request
  679. utils.forEach(requestHeaders, function setRequestHeader(val, key) {
  680. var _header = key.toLowerCase();
  681. if ((typeof requestData === 'undefined' && _header === 'content-type') || _header === 'referer') {
  682. // Remove Content-Type if data is undefined
  683. // And the miniprogram document said that '设置请求的 header,header 中不能设置 Referer'
  684. delete requestHeaders[key];
  685. }
  686. });
  687. mpRequestOption.header = requestHeaders;
  688. // Add responseType to request if needed
  689. if (config.responseType) {
  690. mpRequestOption.responseType = config.responseType;
  691. }
  692. if (config.cancelToken) {
  693. // Handle cancellation
  694. config.cancelToken.promise.then(function onCanceled(cancel) {
  695. if (!requestTask) {
  696. return;
  697. }
  698. requestTask.abort();
  699. reject(cancel);
  700. // Clean up request
  701. requestTask = undefined;
  702. });
  703. }
  704. // Converting JSON strings to objects is handed over to the MiniPrograme
  705. if (isJSONstr(requestData)) {
  706. requestData = JSON.parse(requestData);
  707. }
  708. if (requestData !== undefined) {
  709. mpRequestOption.data = requestData;
  710. }
  711. requestTask = request(transformConfig(mpRequestOption));
  712. });
  713. }
  714. module.exports = mpAdapter;
  715. module.exports.default = mpAdapter;