request.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. //用BASEURL来表示域名地址
  2. // const BASE_URL = 'http://192.168.110.153:9002'
  3. // const BASE_URL = 'https://zswl.api.jpy.wang/zswl-cloud-bdb'
  4. // const BASE_URL = 'https://api.dev.zonelife.cn'
  5. import {
  6. BASE_URL
  7. } from '@/utils/config.js'
  8. //封装请求方法
  9. export const request = (options) => {
  10. return new Promise((resolve, reject) => {
  11. //请求路径拼接,,其中options.url就是通过下面方法myRequest获取到接口部分的url
  12. //method--请求方法,不是method的post就是get
  13. //请求的参数,当没有参数的时候就是空对象
  14. // BASE_URL = BASE_UR.includes('dev') ?
  15. let BASE_URL2 = BASE_URL;
  16. if(options.url.includes('/zswl-cloud-shop')){
  17. BASE_URL2 = 'http://g3710170f8.zicp.fun'
  18. options.url = options.url.replace("/zswl-cloud-shop","")
  19. }
  20. uni.request({
  21. url: BASE_URL2 + options.url,
  22. method: options.method || 'GET',
  23. data: options.data || {},
  24. header: {
  25. accessToken: uni.getStorageSync('token')
  26. },
  27. success: (res) => {
  28. if (res.statusCode !== 200) {
  29. return uni.showToast({
  30. title: '获取失败'
  31. })
  32. // uni.hideLoading()
  33. } else if (res.data.msg != '成功') { //接口返回报错
  34. uni.showToast({
  35. title: res.data.content || res.data.msg || res.data.exception.message || '请求失败',
  36. icon: 'error'
  37. })
  38. console.log('报错:', res);
  39. // token过期或出了问题
  40. if (res.data.exception && res.data.exception.type ==
  41. 'AuthenticationCredentialsNotFoundException')
  42. {
  43. uni.showLoading({
  44. title: '刷新登录中',
  45. })
  46. if (!uni.getStorageSync('refreshToken')) {
  47. uni.clearStorageSync()
  48. uni.reLaunch({
  49. url: '/pages/index/index'
  50. })
  51. }
  52. // 刷新token
  53. uni.request({
  54. url: BASE_URL + '/zswl-cloud-bdb/user/refreshToken',
  55. method: 'GET',
  56. data: {
  57. refreshToken: uni.getStorageSync('refreshToken')
  58. },
  59. success(r) {
  60. uni.hideLoading()
  61. if (r.data.content == '刷新令牌错误') {
  62. uni.showToast({
  63. title: '登录失效',
  64. icon: 'fail'
  65. })
  66. uni.clearStorageSync()
  67. uni.reLaunch({
  68. url: '/pages/index/index'
  69. })
  70. } else {
  71. uni.setStorageSync('token', r.data.content) //登录状态
  72. // 刷新页面
  73. let list = ['/pay/pay']
  74. var pages = getCurrentPages();
  75. var url = '/' + pages[pages.length - 1].route
  76. if(list.indexOf(url) == -1){
  77. console.log(11111111,list.indexOf(url),url);
  78. uni.reLaunch({
  79. url
  80. })
  81. }
  82. }
  83. }
  84. })
  85. }
  86. }
  87. resolve(res.data)
  88. },
  89. //请求失败
  90. fail: (err) => {
  91. uni.showToast({
  92. title: '请求接口失败'
  93. })
  94. reject(err)
  95. }
  96. })
  97. })
  98. }