uni-events-helper-wx
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.4 KiB

3 years ago
  1. // 获取合并的数据
  2. export const mergeConfig = function(_this, options) {
  3. //判断url是不是链接
  4. let urlType = /^(http|https):\/\//.test(options.url);
  5. let config = Object.assign({}, _this.config, options);
  6. if (options.method == "FILE") {
  7. config.url = urlType ? options.url : _this.fileUrl + options.url;
  8. } else {
  9. config.url = urlType ? options.url : _this.baseUrl + options.url;
  10. }
  11. //请求头
  12. if (options.header) {
  13. config.header = Object.assign({}, _this.header, options.header);
  14. } else {
  15. config.header = _this.header;
  16. }
  17. return config;
  18. }
  19. // 请求
  20. export const dispatchRequest = function(requestInfo) {
  21. return new Promise((resolve, reject) => {
  22. let requestData = {
  23. url: requestInfo.url,
  24. header: requestInfo.header, //加入请求头
  25. success: (res) => {
  26. resolve(res);
  27. },
  28. fail: (err) => {
  29. reject(err);
  30. }
  31. };
  32. //请求类型
  33. if (requestInfo.method) {
  34. requestData.method = requestInfo.method;
  35. }
  36. if (requestInfo.data) {
  37. requestData.data = requestInfo.data;
  38. }
  39. // #ifdef MP-WEIXIN || MP-ALIPAY
  40. if (requestInfo.timeout) {
  41. requestData.timeout = requestInfo.timeout;
  42. }
  43. // #endif
  44. if (requestInfo.dataType) {
  45. requestData.dataType = requestInfo.dataType;
  46. }
  47. // #ifndef APP-PLUS || MP-ALIPAY
  48. if (requestInfo.responseType) {
  49. requestData.responseType = requestInfo.responseType;
  50. }
  51. // #endif
  52. // #ifdef H5
  53. if (requestInfo.withCredentials) {
  54. requestData.withCredentials = requestInfo.withCredentials;
  55. }
  56. // #endif
  57. uni.request(requestData);
  58. })
  59. }
  60. // jsonp请求
  61. export const jsonpRequest = function(requestInfo) {
  62. return new Promise((resolve, reject) => {
  63. let dataStr = '';
  64. Object.keys(requestInfo.data).forEach(key => {
  65. dataStr += key + '=' + requestInfo.data[key] + '&';
  66. });
  67. //匹配最后一个&并去除
  68. if (dataStr !== '') {
  69. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  70. }
  71. requestInfo.url = requestInfo.url + '?' + dataStr;
  72. let callbackName = "callback" + Math.ceil(Math.random() * 1000000);
  73. // #ifdef H5
  74. window[callbackName] = function(data) {
  75. resolve(data);
  76. }
  77. let script = document.createElement("script");
  78. script.src = requestInfo.url + "&callback=" + callbackName;
  79. document.head.appendChild(script);
  80. // 及时删除,防止加载过多的JS
  81. document.head.removeChild(script);
  82. // #endif
  83. });
  84. }