node.js - 手动输入 URL 后的 Vue.js 身份验证
问题描述
在我的routes
数组中main.js
,我设置了
meta : { requiresAuth: true }
除了UserLogin
页面上的每个组件。
关于导航分辨率,我在每条路线之前设置了一个检查,如下所示:
router.beforeEach((to, from, next) => {
const currentUser = firebase.auth().currentUser;
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
const currentUserState = !!currentUser;
console.table({ currentUserState, requiresAuth });
if (requiresAuth && !currentUser) {
next('/login');
} else {
next();
}
}
使用此设置,一切几乎都按预期/预期工作。登录的用户可以去任何地方,匿名用户被重定向到localhost/login
.
但是,这种检查和重定向仅在用户通过单击 Web 应用程序中的链接进行导航时起作用(这些都是<router-link>
s that go :to="{ name: 'SomeComponent' }"
.
当任何用户(注册或匿名)尝试通过键入或复制粘贴 url 在应用程序中导航时,应用程序将自动将其发送到登录页面。
从 console.table 输出中,我可以看到手动输入 url 总是导致 currentUserState 为 false。
它不会保持错误:已登录currentUserState === true
(currentUserState === false
currentUserState
true
我只能隐约猜测问题与渲染和firebase.auth()
.
解决方案
firebase.initializeApp(config)
// you need to let firebase try and get the auth state before instantiating the
// the Vue component, otherwise the router will be created and you haven't
// resolved whether or not you have a user
firebase.auth().onAuthStateChanged(function(user) {
app = new Vue({
el: '#app',
template: '<App/>',
components: { App },
router
})
});
推荐阅读
- javascript - TinyMCE 自动关闭标签和/或重新排列它们
- tomcat - 如何从主机访问在虚拟机上运行的 tomcat 实例
- ansible - 当在同一剧本中创建事实文件时,剧本无法读取 local_facts
- go - 覆盖全局变量
- html - 检索表单的字段
- perl - 自动替换服务器中的 exe 文件或 script/myscript.pl
- java - java.lang.IllegalStateException:找不到所需的标识符属性
- python - 无法通过 pip 安装 watson 开发者云模块
- regex - 将日志字符串转换为fail2ban的正则表达式
- arrays - Excel:识别数组公式最终结果中使用的参考行