request.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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.log('报错:', res);
  33. // token过期或出了问题
  34. if (res.data.exception && res.data.exception.type ==
  35. 'AuthenticationCredentialsNotFoundException') {
  36. uni.showLoading({
  37. title: '刷新登录中',
  38. })
  39. if (!uni.getStorageSync('refreshToken')) {
  40. uni.clearStorageSync()
  41. uni.reLaunch({
  42. url: '/pages/index/index'
  43. })
  44. }
  45. // 刷新token
  46. uni.request({
  47. url: BASE_URL + '/zswl-cloud-bdb/user/refreshToken',
  48. method: 'GET',
  49. data: {
  50. refreshToken: uni.getStorageSync('refreshToken')
  51. },
  52. success(r) {
  53. uni.hideLoading()
  54. if (r.data.content == '刷新令牌错误') {
  55. uni.showToast({
  56. title: '登录失效',
  57. icon: 'fail'
  58. })
  59. uni.clearStorageSync()
  60. uni.reLaunch({
  61. url: '/pages/index/index'
  62. })
  63. } else {
  64. uni.setStorageSync('token', r.data.content) //登录状态
  65. // 刷新页面
  66. let list = ['/pay/pay']
  67. var pages = getCurrentPages();
  68. var url = '/' + pages[pages.length - 1].route
  69. if(list.indexOf(url) == -1){
  70. console.log(11111111,list.indexOf(url),url);
  71. uni.reLaunch({
  72. url
  73. })
  74. }
  75. }
  76. }
  77. })
  78. }
  79. }
  80. resolve(res.data)
  81. },
  82. //请求失败
  83. fail: (err) => {
  84. uni.showToast({
  85. title: '请求接口失败'
  86. })
  87. reject(err)
  88. }
  89. })
  90. })
  91. }