request.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import {
  2. $http
  3. } from '@escook/request-miniprogram'
  4. // $http.baseUrl = "http://192.168.0.40:8081"
  5. uni.$http = $http
  6. import {
  7. getToken,
  8. removeAll
  9. } from "./auth.js"
  10. import {
  11. getUserIP
  12. } from './getIP.js'
  13. // getUserIP((ip) => {
  14. // $http.baseUrl = 'http://' + ip + ':8081'
  15. // })
  16. console.log(window.location.origin);
  17. const baseUrl = window.location.origin
  18. $http.baseUrl = baseUrl
  19. // 请求拦截器
  20. $http.beforeRequest = function(options) {
  21. if (getToken()) {
  22. options.header['Authorization'] = 'Bearer ' + getToken()
  23. options.header['token'] = getToken()
  24. }
  25. uni.showLoading({
  26. title: "数据加载中..."
  27. })
  28. }
  29. // 响应拦截器
  30. $http.afterRequest = function(res) {
  31. try {
  32. const code = res.data.code
  33. const msg = res.data.msg
  34. if (code === 401 || code === 403) {
  35. uni.showLoading({
  36. title: msg
  37. })
  38. removeAll()
  39. uni.navigateTo({
  40. url: "/pages/login/index"
  41. })
  42. } else if (code !== 200) {
  43. uni.showToast({
  44. title: msg,
  45. duration: 2000,
  46. icon: "error"
  47. });
  48. uni.hideToast();
  49. } else {
  50. }
  51. uni.hideLoading()
  52. } catch (e) {
  53. }
  54. }