request.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. let apiUrl = 'https://test.api.zanxiangnet.com/miniapp'
  2. let isopen = false // 控制loading
  3. const openLoading = () => {
  4. if (!isopen) {
  5. isopen = true
  6. uni.showLoading({
  7. title: '加载中'
  8. });
  9. }
  10. }
  11. const hiddenLoading = () => {
  12. isopen = false
  13. uni.hideLoading()
  14. }
  15. /**
  16. *
  17. */
  18. // interface Props {
  19. // url: string,
  20. // data?: any,
  21. // config?: {
  22. // header?: any,
  23. // method?: "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT",
  24. // responseType?: "text" | "arraybuffer"
  25. // },
  26. // backspace?: boolean, // 是否返回上一页 默认否
  27. // isLoading?: boolean, // 是否展示loading
  28. // isToast?: boolean // 是否提示
  29. // }
  30. export function request(props) {
  31. let {
  32. url,
  33. data,
  34. config,
  35. method,
  36. backspace = false,
  37. isLoading = true,
  38. isToast = true
  39. } = props
  40. let _loading = false
  41. let reqTimer = null
  42. if (isLoading) {
  43. reqTimer = setTimeout(() => {
  44. openLoading()
  45. _loading = true
  46. }, 500)
  47. }
  48. return new Promise((resolve, reject) => {
  49. uni.request({
  50. url: `${apiUrl}${url}`,
  51. data,
  52. method: method || 'GET',
  53. success: (res) => {
  54. console.log("请求返回数据---》", res)
  55. reqTimer && clearTimeout(reqTimer)
  56. if (_loading) {
  57. hiddenLoading()
  58. }
  59. if (res.data.code === 500) {
  60. uni.showToast({
  61. title: res.data.msg || `${apiUrl}${url}请求错误`,
  62. icon: 'none',
  63. duration: 2000
  64. })
  65. return
  66. }
  67. resolve(res.data)
  68. },
  69. fail: (err) => {
  70. reqTimer && clearTimeout(reqTimer)
  71. if (_loading) {
  72. hiddenLoading()
  73. }
  74. reject(`${url}接口调用失败${err}`)
  75. }
  76. })
  77. })
  78. }