request.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 {BASE_URL} from '@/utils/config.js'
  6. //封装请求方法
  7. export const request = (options) => {
  8. return new Promise((resolve, reject) => {
  9. //请求路径拼接,,其中options.url就是通过下面方法myRequest获取到接口部分的url
  10. //method--请求方法,不是method的post就是get
  11. //请求的参数,当没有参数的时候就是空对象
  12. uni.request({
  13. url:BASE_URL +options.url,
  14. method: options.method || 'GET',
  15. data: options.data || {},
  16. header: {
  17. accessToken: uni.getStorageSync('token')
  18. },
  19. success: (res) => {
  20. if (res.statusCode !== 200) {
  21. return uni.showToast({
  22. title: '获取失败'
  23. })
  24. // uni.hideLoading()
  25. } else if (res.data.msg != '成功') {//接口返回报错
  26. uni.showToast({
  27. title: res.data.msg||res.data.exception.message || '请求失败',
  28. icon: 'error'
  29. })
  30. console.log('报错:', res);
  31. // token过期或出了问题
  32. if (res.data.exception&&res.data.exception.type ==
  33. 'AuthenticationCredentialsNotFoundException') {
  34. if(!uni.getStorageSync('refreshToken')){
  35. uni.showToast({
  36. title:'登录失效',
  37. icon:'fail'
  38. })
  39. uni.clearStorageSync()
  40. uni.reLaunch({
  41. url:'/pages/index/index'
  42. })
  43. }
  44. // 刷新token
  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. if(r.data.content == '刷新令牌错误'){
  53. uni.showToast({
  54. title:'登录失效',
  55. icon:'fail'
  56. })
  57. uni.clearStorageSync()
  58. uni.reLaunch({
  59. url:'/pages/index/index'
  60. })
  61. }else{
  62. uni.setStorageSync('token', r.data.content) //登录状态
  63. // 刷新页面
  64. var pages = getCurrentPages();
  65. var url = '/' + pages[pages.length - 1].route
  66. uni.reLaunch({
  67. url
  68. })
  69. }
  70. }
  71. })
  72. }
  73. }
  74. resolve(res.data)
  75. },
  76. //请求失败
  77. fail: (err) => {
  78. uni.showToast({
  79. title: '请求接口失败'
  80. })
  81. reject(err)
  82. }
  83. })
  84. })
  85. }