request.js 1.5 KB

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