request.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. uni.request({
  15. url: BASE_URL + options.url,
  16. method: options.method || 'GET',
  17. data: options.data || {},
  18. header: {
  19. accessToken: uni.getStorageSync('token')
  20. },
  21. success: (res) => {
  22. if (res.statusCode !== 200) {
  23. return uni.showToast({
  24. title: '获取失败'
  25. })
  26. // uni.hideLoading()
  27. } else if (res.data.msg != '成功') { //接口返回报错
  28. uni.showToast({
  29. title: res.data.content || res.data.msg || res.data.exception.message || '请求失败',
  30. icon: 'error'
  31. })
  32. console.error('报错接口:',BASE_URL + options.url,'报错信息:', res.data);
  33. // token过期或出了问题
  34. if (res.data.exception && res.data.exception.type ==
  35. 'AuthenticationCredentialsNotFoundException') {
  36. uni.showToast({
  37. title: '登录过期',
  38. icon: 'error'
  39. })
  40. if (uni.getStorageSync('refreshToken') && uni.getStorageSync('token') ) {
  41. // 刷新token
  42. uni.showLoading({
  43. title: '刷新登录中',
  44. })
  45. uni.request({
  46. url: BASE_URL + '/zswl-cloud-bdb/user/refreshToken',
  47. method: 'GET',
  48. data: {
  49. refreshToken: uni.getStorageSync('refreshToken')
  50. },
  51. success(r) {
  52. uni.hideLoading()
  53. if (r.data.content == '刷新令牌错误') {
  54. uni.showToast({
  55. title: '登录失效',
  56. icon: 'fail'
  57. })
  58. uni.clearStorageSync()
  59. uni.reLaunch({
  60. url: '/pages/index/index'
  61. })
  62. } else {
  63. uni.setStorageSync('token', r.data.content) //登录状态
  64. // 刷新页面
  65. let list = ['/pay/pay']
  66. var pages = getCurrentPages();
  67. var url = '/' + pages[pages.length - 1].route
  68. if(list.indexOf(url) == -1){
  69. uni.reLaunch({
  70. url
  71. })
  72. }
  73. }
  74. }
  75. })
  76. }else{
  77. uni.showModal({
  78. title:'请登录',
  79. confirmText:'去登录',
  80. success(res){
  81. if(res.confirm){
  82. var pages = getCurrentPages()
  83. var url = '/' + pages[pages.length - 1].route
  84. uni.reLaunch({
  85. url:'/login/login/login?redirect='+url
  86. })
  87. }
  88. }
  89. })
  90. }
  91. }
  92. }
  93. resolve(res.data)
  94. },
  95. //请求失败
  96. fail: (err) => {
  97. uni.showToast({
  98. title: '请求接口失败'
  99. })
  100. reject(err)
  101. }
  102. })
  103. })
  104. }