request.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import {baseApiUrl} from './config.js'
  2. import {apiWechatLogin} from '@/api/user'
  3. import store from '@/store/index'
  4. // 请求错误消息提示
  5. const showError=error=>{
  6. let errMsg=''
  7. switch(error.Ret){
  8. case 400:
  9. errMsg='请求参数错误';
  10. break;
  11. default:
  12. errMsg=error.ErrMsg;
  13. break;
  14. }
  15. uni.showToast({
  16. title:errMsg,
  17. icon:'none'
  18. })
  19. }
  20. // 微信登录
  21. const wechatLogin=()=>{
  22. return new Promise((resolve,reject)=>{
  23. uni.login({
  24. provider: 'weixin',
  25. success: function (loginRes) {
  26. apiWechatLogin({code:loginRes.code}).then(res=>{
  27. if(res.code===200){
  28. store.commit('setToken', res.data.authorization)
  29. resolve(res.data)
  30. }
  31. })
  32. },
  33. fail:function(loginErr){
  34. uni.showToast({
  35. title:"微信登录失败",
  36. icon:"none"
  37. })
  38. }
  39. })
  40. })
  41. }
  42. let requestList=[]//存放token失效时请求队列
  43. let isRefreshing=false//是否正在刷新token
  44. /**
  45. * 刷新token
  46. */
  47. const refreshToken=async (url,params,method,resolve)=>{
  48. requestList.push(()=>{resolve(http(url,params,method))})
  49. if(!isRefreshing){
  50. isRefreshing=true
  51. const wechatLoginRes=await wechatLogin()
  52. console.log(wechatLoginRes);
  53. if(!wechatLoginRes.is_bind){
  54. uni.navigateTo({
  55. url:'/pages/login'
  56. })
  57. return
  58. }
  59. // 重新请求队列
  60. requestList.map(MT=>{MT()})
  61. requestList=[]
  62. isRefreshing=false
  63. }
  64. }
  65. let LOADINGCOUNT = 0;// 请求数
  66. const http=(url,params,method)=>{
  67. // 设置loading
  68. if (LOADINGCOUNT === 0) {
  69. uni.showLoading({
  70. title:'加载中...'
  71. })
  72. }
  73. LOADINGCOUNT++;
  74. return new Promise((resolve,reject)=>{
  75. uni.request({
  76. url:baseApiUrl+url,
  77. data:params,
  78. method:method,
  79. header:{
  80. Authorization:store.state.user.token,
  81. },
  82. success(res) {
  83. if(res.data.code!==200){
  84. showError(res.data)
  85. }
  86. // 401 token失效
  87. if(res.data.code===401){
  88. refreshToken(url,params,method,resolve)
  89. return
  90. }
  91. resolve(res.data)
  92. },
  93. fail(error) {
  94. console.log(error);
  95. uni.showToast({
  96. title:'服务器错误',
  97. icon:'none'
  98. })
  99. },
  100. complete() {
  101. // 关闭loading
  102. LOADINGCOUNT--;
  103. if (LOADINGCOUNT === 0) {
  104. uni.hideLoading()
  105. }
  106. }
  107. })
  108. })
  109. }
  110. // get 请求
  111. export const httpGet=(url,params)=>{
  112. return http(url,params,'GET')
  113. }
  114. // post 请求
  115. export const httpPost=(url,params)=>{
  116. return http(url,params,'POST')
  117. }