router.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. uni.addInterceptor('request', {
  2. invoke(args) {
  3. // request 触发前拼接 url
  4. const {
  5. data,
  6. method,
  7. } = args;
  8. if (method === "GET") {
  9. // 如果是get请求,且params是数组类型如arr=[1,2],则转换成arr=1&arr=2
  10. const newData = qs.stringify(data, {
  11. arrayFormat: "repeat"
  12. })
  13. delete args.data;
  14. args.url = `${args.url}?${newData}`;
  15. }
  16. },
  17. success(args) {},
  18. fail(err) {},
  19. complete(res) {}
  20. })
  21. import config from "./config.js"
  22. export default function initApp() {
  23. /**
  24. * 页面跳转拦截器
  25. */
  26. let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
  27. list.forEach(item => { //用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
  28. uni.addInterceptor(item, {
  29. invoke(e) { // 调用前拦截
  30. //获取用户的token
  31. const token = uni.getStorageSync('uni_id_token'),
  32. //token是否已失效
  33. tokenExpired = uni.getStorageSync('uni_id_token_expired') < Date.now(),
  34. //获取要跳转的页面路径(url去掉"?"和"?"后的参数)
  35. url = e.url.split('?')[0];
  36. let notNeed = config.whiteList.includes(url)
  37. // 如果在whiteList里面就不需要登录
  38. if (notNeed) {
  39. return e
  40. } else {
  41. //需要登录
  42. if (token == '' || tokenExpired) {
  43. uni.showToast({
  44. title: '请先登录',
  45. icon: 'none'
  46. })
  47. uni.navigateTo({
  48. url: config.loginPage
  49. })
  50. return false
  51. }else{
  52. return e
  53. }
  54. }
  55. },
  56. fail(err) { // 失败回调拦截
  57. console.log(err);
  58. if (Debug) {
  59. console.log(err);
  60. uni.showModal({
  61. content: JSON.stringify(err),
  62. showCancel: false
  63. });
  64. }
  65. }
  66. })
  67. })
  68. //添加uniCloud云函数拦截器
  69. }