一. uniapp 拦截器
uni.addInterceptor(STRING, OBJECT)
注意: 拦截参数,拦截的是 api 名称, 如:uni.addInterceptor('request', OBJECT) ,将拦截 uni.request()
二. 通过校验白名单路径, 拦截跳转登录页获取Token, 然后继续正常的业务.
- App.vue
import { initRouteGuard } from '@/common/interceptor.js'
onLaunch: function() {
initRouteGuard() // 加载拦截器
console.log('App Launch')
},
- 新建拦截器 JS 文件, interceptor.js
// 名称:全局路由拦截器
// 功能:路由导航守卫
// 使用:在 App.vue 的 onLaunch 中调用 initRouteGuard()
// 1. 路由配置
const routeConfig = {
// 设置白名单
whiteList: new Set([
'/pages/jobReport/webLogin'
]),
};
// 2. 核心校验逻辑
const checkRouter = (url) => {
const path = url.split('?')[0];
console.log('-- 拦截器 --:', url);
// 放行白名单
if (routeConfig.whiteList.has(path)) {
return true;
}
// 这段代码的作用是检查是否存在有效的 token:
// 存在有效 token 时返回 true
// 不存在有效 token 时返回 false
return !!uni.getStorageSync('ssToken');
}
// 3. 拦截器核心方法
const routeInterceptor = {
invoke(args) {
console.log('11====启用拦截器', args);
/**
return false; // 放行跳转到下一页
return true; // 拦截,不跳转,跳转到登录页面
*/
let url = args.url // 获取要跳转的页面路径和参数
let path = url.split('?')[0] // 只获取路径
// 只允许白名单内的页面跳转 或者 token 有效
if (checkRouter(path)) {
return true
}
// 这里使用 navigateTo 跳转登录页, 在登录页使用redirectTo 这样可以登录成功后获取 token, 根据 token 关闭登录页, 并跳转到下一页.
uni.navigateTo({
url: '/pages/port/login?redirect=' + encodeURIComponent(url), // 将要跳转的页面路径作为参数传递给登录页面
});
return false
}
};
// 4. 初始化方法
export function initRouteGuard() {
// 注册拦截器
uni.addInterceptor('navigateTo', routeInterceptor);
uni.addInterceptor('redirectTo', routeInterceptor);
uni.addInterceptor('reLaunch', routeInterceptor);
uni.addInterceptor('switchTab', routeInterceptor);
console.log('启动路由守卫');
}
登录页:
// 登录成功后, 同步 token, 跳转传过来的页面.
uni.setStorageSync('ssToken', 'abc12312313')
let path = decodeURIComponent(this.redirect)
// 注意:这里用的redirectTo, 登录成功后可关闭登录页
uni.redirectTo({
url: path,
})