request.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // uni-app请求封装
  2. export default class Request {
  3. // 添加一个计数器,确保多个请求不会互相干扰
  4. static loadingCount = 0;
  5. http(router, data = {}, method, contentType) {
  6. let that = this;
  7. // let path = 'http://nd383294.natappfree.cc'//余红奇
  8. // let path = 'https://live.test.ylrztop.com/prod-api'//余红奇
  9. // let path = 'http://v56c9b8e.natappfree.cc'//余红奇
  10. // let path = 'http://192.168.10.170:7114'//陈果
  11. let path = 'http://192.168.10.166:7114' //余红奇
  12. // let path = 'http://h5api.wxcourse.cdwjyyh.com'
  13. uni.setStorageSync('requestPath', path)
  14. // 只在第一个请求时显示loading
  15. if (Request.loadingCount === 0) {
  16. uni.showLoading({
  17. title: '加载中',
  18. mask: true
  19. });
  20. }
  21. Request.loadingCount++;
  22. return new Promise((resolve, reject) => {
  23. let token = uni.getStorageSync('AppToken');
  24. var httpContentType = 'application/x-www-form-urlencoded';
  25. if (contentType != undefined) {
  26. //application/json;charset=UTF-8
  27. httpContentType = contentType;
  28. }
  29. var routers = router;
  30. // 请求
  31. uni.request({
  32. header: {
  33. // 'Content-Type': 'application/x-www-form-urlencoded',
  34. 'Content-Type': httpContentType,
  35. 'AppToken': token
  36. },
  37. url: `${path}${router}`,
  38. data: data,
  39. method: method,
  40. success: (res) => {
  41. //收到开发者服务器成功返回的回调函数
  42. if (res.code == 401) { //没有权限直接退出到登录界面
  43. let pages = getCurrentPages();
  44. let url = pages[pages.length - 1]; //当前页页面实例
  45. //如果登录界面已打开,自动关闭
  46. if (url != undefined && url.route == "/pages/home/index") {
  47. resolve(res.data)
  48. return;
  49. }
  50. uni.reLaunch({
  51. url: '/pages/home/index'
  52. });
  53. return;
  54. }
  55. if (res.token) {
  56. uni.setStorageSync('AppToken', res.token)
  57. }
  58. resolve(res.data)
  59. },
  60. fail: (res) => {
  61. //接口调用失败的回调函数
  62. },
  63. complete: (res) => {
  64. // 确保每次请求完成都减少计数器
  65. Request.loadingCount--;
  66. // 当所有请求都完成时才隐藏loading
  67. if (Request.loadingCount <= 0) {
  68. uni.hideLoading();
  69. Request.loadingCount = 0; // 重置计数器
  70. }
  71. }
  72. })
  73. })
  74. }
  75. }