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

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