request.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // let apiUrl = 'https://test.api.zanxiangnet.com/miniapp'
  2. let apiUrl = 'https://api.zanxiangnet.com/miniapp'
  3. let isopen = false // 控制loading
  4. const openLoading = () => {
  5. if (!isopen) {
  6. isopen = true
  7. uni.showLoading({
  8. title: '加载中'
  9. });
  10. }
  11. }
  12. const hiddenLoading = () => {
  13. isopen = false
  14. uni.hideLoading()
  15. }
  16. export function request(props) {
  17. let {
  18. url,
  19. data,
  20. config,
  21. method,
  22. backspace = false,
  23. isLoading = true,
  24. isToast = true
  25. } = props
  26. let _loading = false
  27. let reqTimer = null
  28. if (isLoading) {
  29. reqTimer = setTimeout(() => {
  30. openLoading()
  31. _loading = true
  32. }, 500)
  33. }
  34. return new Promise((resolve, reject) => {
  35. uni.request({
  36. url: `${apiUrl}${url}`,
  37. data,
  38. method: method || 'GET',
  39. success: (res) => {
  40. console.log("请求返回数据---》", res)
  41. reqTimer && clearTimeout(reqTimer)
  42. if (_loading) {
  43. hiddenLoading()
  44. }
  45. if (res.data.code === 500) {
  46. uni.showToast({
  47. title: res.data.msg || `${apiUrl}${url}请求错误`,
  48. icon: 'none',
  49. duration: 2000
  50. })
  51. return
  52. }
  53. resolve(res.data)
  54. },
  55. fail: (err) => {
  56. reqTimer && clearTimeout(reqTimer)
  57. if (_loading) {
  58. hiddenLoading()
  59. }
  60. reject(`${url}接口调用失败${err}`)
  61. }
  62. })
  63. })
  64. }