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