request.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const BASE_URL = 'http://192.168.1.222:8088'
  2. // const BASE_URL = 'https://api.xyyxt.net'
  3. // const BASE_URL = 'http://127.0.0.1:8088'
  4. // const BASE_URL = 'https://api.xyyxt.net' //
  5. import store from '@/store/index.js'
  6. import api from './api.js'
  7. var num = 1
  8. var refreshIng = false
  9. export const myRequest = (options) => {
  10. // uni.showLoading({
  11. // title:'拼命加载中...'
  12. // })
  13. return new Promise((resolve, reject) => {
  14. uni.request({
  15. url: BASE_URL + options.url,
  16. method: options.method || 'GET',
  17. data: options.data,
  18. header: options.noToken ? {} : {
  19. AuthorizationToken: 'WX ' + uni.getStorageSync('token')
  20. },
  21. success: async (res) => {
  22. if (res.data.code == 401) {
  23. if (num <= 3) {
  24. if (!uni.getStorageSync('union_id')) {
  25. uni.navigateTo({
  26. url: '/pages/login/login'
  27. });
  28. } else {
  29. num++
  30. res = await doRequest(options)
  31. }
  32. };
  33. }
  34. resolve(res)
  35. },
  36. fail: (err) => {
  37. uni.showToast({
  38. title: "请求接口失败",
  39. icon: 'none'
  40. })
  41. reject(JSON.stringify(err))
  42. }
  43. // complete:()=>{
  44. // uni.hideLoading()
  45. // }
  46. })
  47. })
  48. async function doRequest(response) {
  49. var datas = {
  50. url: '/refreshToken/' + uni.getStorageSync('union_id'),
  51. method: 'get',
  52. noToken: true
  53. }
  54. refreshIng = true //防止同时多次刷新令牌
  55. const res = await myRequest(datas)
  56. refreshIng = false
  57. if (res.data.code === 200) {
  58. uni.setStorageSync('token', res.data.data.token)
  59. var userInfo = {
  60. url: '/getInfo',
  61. method: 'get',
  62. }
  63. const resUser = await myRequest(userInfo)
  64. if (resUser.data.code === 200) {
  65. store.state.userInfo = resUser.data.data
  66. }
  67. let onset = await myRequest(response)
  68. return onset
  69. } else {
  70. uni.navigateTo({
  71. url: '/pages/login/login'
  72. });
  73. }
  74. }
  75. }