湘妃到家前端代码仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

140 lines
2.4 KiB

1 month ago
  1. function http(uri, data, callback, method = 'GET', showLoading, title) {
  2. if(showLoading){
  3. uni.showLoading({
  4. title: title || '正在提交...'
  5. });
  6. }
  7. uni.request({
  8. url: import.meta.env.VITE_GLOB_API + uri,
  9. data: enhanceData(data),
  10. method: method,
  11. header: {
  12. 'X-Access-Token': localStorage.getItem('token'),
  13. 'Content-Type' : method == 'POST' ? 'application/x-www-form-urlencoded' : 'application/json'
  14. },
  15. success: (res) => {
  16. if(showLoading){
  17. uni.hideLoading();
  18. }
  19. if(res.statusCode == 401){
  20. localStorage.removeItem('token')
  21. localStorage.removeItem('userInfo')
  22. console.error('登录过期');
  23. uni.navigateTo({
  24. url: '/pages/login/login'
  25. })
  26. }
  27. //后端接口token出现问题
  28. if(res.data && res.data.code == 500 && res.data.message == '操作失败,token非法无效!'){
  29. localStorage.removeItem('token')
  30. localStorage.removeItem('userInfo')
  31. console.error('登录过期');
  32. uni.navigateTo({
  33. url: '/pages/login/login'
  34. })
  35. }
  36. if(res.statusCode == 200 && res.data.code != 200){
  37. uni.showToast({
  38. mask: true,
  39. duration: 1000,
  40. title: res.data.message,
  41. });
  42. }
  43. callback(res.data)
  44. },
  45. fail: () => {
  46. uni.showLoading({})
  47. setTimeout(()=>{
  48. uni.hideLoading()
  49. uni.showToast({icon:"none", title:"网络异常"})
  50. }, 3000)
  51. if(showLoading){
  52. uni.hideLoading();
  53. }
  54. }
  55. });
  56. }
  57. function deleted(uri, data, callback) {
  58. http(uri, data, callback, 'DELETE')
  59. }
  60. function post(uri, data, callback) {
  61. http(uri, data, callback, 'POST')
  62. }
  63. function get(uri, data, callback) {
  64. http(uri, data, callback, 'GET')
  65. }
  66. function enhanceData(data) {
  67. const userid = uni.getStorageSync("userid")
  68. if (!data) {
  69. data = {}
  70. }
  71. if (userid) {
  72. data.userid = userid
  73. }
  74. return data
  75. }
  76. function sync(method, uri, data) {
  77. return new Promise((resolve, reject) => {
  78. uni.request({
  79. url: uri,
  80. data: data,
  81. method: method,
  82. header: {
  83. 'auth': '1AS9F1HPC4FBC9EN00J7KX2L5RJ99XHZ'
  84. },
  85. success: (res) => {
  86. resolve(res.data)
  87. },
  88. fail: (err) => {
  89. reject(err);
  90. }
  91. })
  92. })
  93. }
  94. let cache = null
  95. function async (method, uri, data) {
  96. const promise = sync(method, uri, data).then(res => {
  97. cache = res
  98. }).catch(err => {
  99. })
  100. }
  101. function syncHttp(uri, data, method = 'GET') {
  102. async (method, uri, data)
  103. }
  104. export default {
  105. http: http,
  106. delete: deleted,
  107. post: post,
  108. get: get,
  109. syncHttp: syncHttp
  110. }