request.js 972 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. // 请求拦截器
  17. $http.beforeRequest = function(options) {
  18. if (getToken()) {
  19. options.header['Authorization'] = 'Bearer ' + getToken()
  20. options.header['token'] = getToken()
  21. }
  22. uni.showLoading({
  23. title: "数据加载中..."
  24. })
  25. }
  26. // 响应拦截器
  27. $http.afterRequest = function(res) {
  28. try {
  29. const code = res.data.code
  30. const msg = res.data.msg
  31. if (code === 401 || code === 403) {
  32. uni.showLoading({
  33. title: msg
  34. })
  35. removeAll()
  36. uni.navigateTo({
  37. url: "/pages/login/index"
  38. })
  39. } else if (code !== 200) {
  40. uni.showToast({
  41. title: msg,
  42. duration: 2000,
  43. icon: "error"
  44. });
  45. uni.hideToast();
  46. } else {
  47. }
  48. uni.hideLoading()
  49. } catch (e) {
  50. }
  51. }