request.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import config from "../config/index.js";
  2. import { showLoadingToast, showToast, closeToast } from "vant";
  3. import "vant/lib/toast/style/index";
  4. function getdata(data) {
  5. let text = "";
  6. for (const key in data) {
  7. text += key + "=" + data[key] + "&";
  8. }
  9. text ? (text = "?" + text) : "";
  10. text = text.replace(/&$/, "");
  11. return text;
  12. }
  13. export default function (ori) {
  14. let baseurl = config.base[ori.urlType || "ajax"];
  15. let url = baseurl + ori.url;
  16. let isEnd = false;
  17. let noToast = ori.noToast;
  18. let defaultErrorToast = ori.errorToast || "请求失败!";
  19. let time = setTimeout(() => {
  20. clearTimeout(time);
  21. !isEnd &&
  22. !ori.noLoad &&
  23. showLoadingToast({
  24. message: "加载中...",
  25. forbidClick: true,
  26. duration: 0,
  27. });
  28. }, 300);
  29. return new Promise((resolve, reject) => {
  30. var xhttp;
  31. if (window.XMLHttpRequest) xhttp = new XMLHttpRequest();
  32. else if (window.ActiveXObject)
  33. xhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
  34. let method = ori.method.toUpperCase();
  35. if (method === "GET") url += getdata(ori.data || {});
  36. xhttp.open(method, url, true);
  37. const headers = Object.keys(ori.header);
  38. for (let i = 0; i < headers.length; i++) {
  39. let key = headers[i];
  40. if (key === 'contentType') {
  41. key = 'Content-Type';
  42. ori.header[key] = ori.header['contentType']
  43. }
  44. xhttp.setRequestHeader(key, ori.header[key]);
  45. }
  46. if (ori.isFormData) {
  47. xhttp.send(ori.data);
  48. } else {
  49. xhttp.setRequestHeader("Content-type", 'application/json');
  50. method === "GET" ? xhttp.send() : xhttp.send(JSON.stringify(ori.data));
  51. }
  52. xhttp.onreadystatechange = function () {
  53. if (this.readyState != 4) return;
  54. isEnd = true;
  55. closeToast();
  56. if (this.status != 200) {
  57. let t = JSON.parse(this.responseText || "{}");
  58. !noToast && showToast(t.message || defaultErrorToast);
  59. reject(t);
  60. return;
  61. }
  62. let data = {};
  63. try {
  64. data =
  65. this.responseText !== "null"
  66. ? JSON.parse(this.responseText || "{}")
  67. : {};
  68. } catch (err) {
  69. !noToast && showToast(defaultErrorToast);
  70. console.error(err);
  71. reject(err);
  72. }
  73. if (data.code === 0 || ori.next) resolve(data.data || data);
  74. else reject(data);
  75. };
  76. });
  77. }