request.js 930 B

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