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

134 lines
2.2 KiB

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