request.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import App from '@/App.vue'
  2. import store from '@/store/index.js'; //在js文件引入store模块
  3. import Vue from 'vue'
  4. import Vuex from 'vuex'
  5. import {
  6. getSign
  7. } from './appsecret.js';
  8. function guid2() {
  9. function S4() {
  10. return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  11. }
  12. return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
  13. }
  14. let tiem;
  15. function http(options) {
  16. return new Promise((resolve, reject) => {
  17. let settingFile = Vue.prototype.$siteinfo;
  18. let author = Vue.prototype.$author;
  19. let token = uni.getStorageSync('token') || '';
  20. let data = options.data || {};
  21. let time = parseInt(new Date().getTime() / 1000)
  22. data.version = settingFile.version;
  23. data.token = token;
  24. // #ifdef H5
  25. data.unid = Vue.prototype.$uuid;
  26. // #endif
  27. // #ifndef H5
  28. data.unid = settingFile.uniacid;
  29. // #endif
  30. var sdata={
  31. unid:data.unid,
  32. version:data.version
  33. };
  34. data.sign = getSign(sdata, time)
  35. data.time = time;
  36. let baseUrl = settingFile.siteroot;
  37. // #ifdef H5
  38. baseUrl = Vue.prototype.$siteinfo.h5_siteroot;
  39. // #endif
  40. let purl = baseUrl + options.url;
  41. if (author.we7_v2 == 1) {
  42. purl = baseUrl + '/addons/yq_breedingmall/index.php' + options.url;
  43. }
  44. // console.log('purl', purl)
  45. // console.log('data', JSON.stringify(data))
  46. var setting = {
  47. url: purl,
  48. data: data,
  49. method: options.method.toUpperCase() || 'GET',
  50. timeout: 60000,
  51. header: {
  52. 'content-type': 'application/x-www-form-urlencoded', // from data
  53. },
  54. success(res) {
  55. if (res.data.status == 401) {
  56. console.log('进入了')
  57. uni.showToast({
  58. title: res.data.msg,
  59. icon: 'none',
  60. duration: 1000
  61. })
  62. store.commit('logout')
  63. uni.clearStorage()
  64. if (tiem) clearTimeout(tiem)
  65. tiem = setTimeout(() => {
  66. console.log('进入判断')
  67. uni.switchTab({
  68. url: '/pages/user/user'
  69. })
  70. }, 1000)
  71. }
  72. resolve(res.data);
  73. uni.hideLoading();
  74. },
  75. fail(err) {
  76. console.log('res', JSON.stringify(err))
  77. uni.showToast({
  78. icon: 'error',
  79. title: '网络超时!'
  80. })
  81. reject(err);
  82. },
  83. }
  84. if (options.files) {
  85. setting.files = Object.assign(setting.files, options.files);
  86. }
  87. if (options.header) {
  88. setting.header = Object.assign(setting.header, options.header);
  89. }
  90. uni.request(setting);
  91. }).catch(error => {
  92. console.log('error', JSON.stringify(error))
  93. reject(error)
  94. });
  95. }
  96. export default http;