瑶都万能墙
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.

139 lines
2.3 KiB

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