request.js 1.6 KB

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