request.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { log } from '@/utils/base.js';
  2. import store from "@/store/index.js";
  3. const host = "https://www.shvber.com/"
  4. const baseUrl = "api/"
  5. const request = (url, data, type = "get", header = {}, onlyHost = false, loading = true) => {
  6. if (loading) {
  7. uni.showLoading();
  8. }
  9. return new Promise((resolve, reject) => {
  10. uni.request({
  11. method: type,
  12. url: `${host}${onlyHost?"":baseUrl}${url}`,
  13. data: data,
  14. dataType: "json",
  15. header: {
  16. "content-type": "application/json;charset=UTF-8",
  17. "Authorization": store.state.token,
  18. "cid": "",
  19. ...header
  20. },
  21. success: (res) => {
  22. log(`${type}==>${url}`, data, res);
  23. resolve(res.data);
  24. },
  25. fail: (err) => {
  26. reject(err);
  27. },
  28. complete: () => {
  29. if (loading) {
  30. setTimeout(() => { uni.hideLoading(); }, 200)
  31. }
  32. }
  33. })
  34. })
  35. }
  36. const defaultOptions = {
  37. url: "",
  38. data: undefined,
  39. type: "post",
  40. header: undefined,
  41. onlyHost: false,
  42. loading: true
  43. }
  44. const post = (url, options) => {
  45. let opts = { ...defaultOptions };
  46. if (typeof url == "string") {
  47. opts.url = url;
  48. if (typeof options == "object") {
  49. opts = { ...opts, ...options }
  50. }
  51. } else {
  52. opts = { ...opts, ...url }
  53. }
  54. if (!opts.url) {
  55. log("POST请求url不能为空")
  56. throw new Error("POST请求url不能为空")
  57. }
  58. return request(opts.url, opts.data, "post", opts.header, opts.onlyHost, opts.loading);
  59. }
  60. const get = (url, options) => {
  61. let opts = { ...defaultOptions };
  62. if (typeof url == "string") {
  63. opts.url = url;
  64. if (typeof options == "object") {
  65. opts = { ...opts, ...options }
  66. }
  67. } else {
  68. opts = { ...opts, ...options }
  69. }
  70. if (!opts.url) {
  71. log("GET请求url不能为空")
  72. throw new Error("GET请求url不能为空")
  73. }
  74. return request(opts.url, opts.data, "get", opts.header, opts.onlyHost, opts.loading);
  75. }
  76. export {
  77. request,
  78. post,
  79. get
  80. }