推广小程序前端代码
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.

135 lines
2.2 KiB

2 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' : 'application/x-www-form-urlencoded'
  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. && res.data.code != 902){
  30. uni.showToast({
  31. mask: true,
  32. duration: 1000,
  33. title: res.data.message,
  34. icon:'none'
  35. });
  36. }
  37. callback(res.data)
  38. },
  39. fail: () => {
  40. uni.showLoading({})
  41. setTimeout(()=>{
  42. uni.hideLoading()
  43. uni.showToast({icon:"none", title:"网络异常"})
  44. }, 3000)
  45. if(showLoading){
  46. uni.hideLoading();
  47. }
  48. }
  49. });
  50. }
  51. function deleted(uri, data, callback) {
  52. http(uri, data, callback, 'DELETE')
  53. }
  54. function post(uri, data, callback) {
  55. http(uri, data, callback, 'POST')
  56. }
  57. function get(uri, data, callback) {
  58. http(uri, data, callback, 'GET')
  59. }
  60. function enhanceData(data) {
  61. const userid = uni.getStorageSync("userid")
  62. if (!data) {
  63. data = {}
  64. }
  65. if (userid) {
  66. data.userid = userid
  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: {
  77. 'auth': '1AS9F1HPC4FBC9EN00J7KX2L5RJ99XHZ'
  78. },
  79. success: (res) => {
  80. resolve(res.data)
  81. },
  82. fail: (err) => {
  83. reject(err);
  84. }
  85. })
  86. })
  87. }
  88. let cache = null
  89. function async (method, uri, data) {
  90. const promise = sync(method, uri, data).then(res => {
  91. cache = res
  92. }).catch(err => {
  93. })
  94. }
  95. function syncHttp(uri, data, method = 'GET') {
  96. async (method, uri, data)
  97. }
  98. export default {
  99. http: http,
  100. delete: deleted,
  101. post: post,
  102. get: get,
  103. syncHttp: syncHttp
  104. }