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.

130 lines
2.2 KiB

8 months 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': uni.getStorageSync('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 || res.data.message === '操作失败,用户不存在!'){
  20. uni.removeStorageSync('token')
  21. uni.removeStorageSync('userInfo')
  22. uni.navigateTo({
  23. url: '/pages/login/mobile'
  24. })
  25. }
  26. if(res.statusCode == 200 && res.data.code != 200){
  27. uni.showToast({
  28. mask: true,
  29. duration: 1000,
  30. title: res.data.message,
  31. });
  32. }
  33. callback(res.data)
  34. },
  35. fail: () => {
  36. uni.showLoading({})
  37. setTimeout(()=>{
  38. uni.hideLoading()
  39. uni.showToast({icon:"none", title:"网络异常"})
  40. }, 3000)
  41. if(showLoading){
  42. uni.hideLoading();
  43. }
  44. }
  45. });
  46. }
  47. function deleted(uri, data, callback){
  48. http(uri, data, callback, 'DELETE')
  49. }
  50. function post(uri, data, callback){
  51. http(uri, data, callback, 'POST')
  52. }
  53. function get(uri, data, callback){
  54. http(uri, data, callback, 'GET')
  55. }
  56. function enhanceData(data){
  57. const userid = uni.getStorageSync("userid")
  58. const enter_id = uni.getStorageSync("enter_id")
  59. if (!data){
  60. data = {}
  61. }
  62. if (userid){
  63. data.userid = userid
  64. }
  65. if (enter_id){
  66. data.enter_id = enter_id
  67. }
  68. return data
  69. }
  70. function sync(method, uri, data){
  71. return new Promise((resolve, reject) => {
  72. uni.request({
  73. url: uri,
  74. data: data,
  75. method: method,
  76. header: { 'auth': '1AS9F1HPC4FBC9EN00J7KX2L5RJ99XHZ' },
  77. success: (res) => {
  78. resolve(res.data)
  79. },
  80. fail: (err) => {
  81. reject(err);
  82. }
  83. })
  84. })
  85. }
  86. let cache = null
  87. function async(method, uri, data){
  88. const promise = sync(method, uri, data).then(res => {
  89. cache = res
  90. }).catch(err => {
  91. })
  92. }
  93. function syncHttp(uri, data, method = 'GET'){
  94. async(method, uri, data)
  95. }
  96. export default {
  97. http: http,
  98. delete: deleted,
  99. post: post,
  100. get: get,
  101. syncHttp: syncHttp
  102. }