【发布时间】:2019-03-17 05:24:37
【问题描述】:
在我的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 和 :to="{ name: 'SomeComponent' }"。
当任何用户(注册或匿名)尝试通过键入或复制粘贴 URL 来浏览应用程序时,应用程序会自动将其发送到登录页面。
从console.table 输出中,我可以看到手动输入url 总是导致currentUserState 为false。
它不会保持错误:已登录 (currentUserState === true) 的用户,然后手动导航到某处 (currentUserState === false),其 currentUserState 恢复为 true
我只能隐约猜测问题与渲染和firebase.auth()有关。
【问题讨论】:
-
需要看看你是如何初始化firebase的......我猜你是在初始化firebase之前设置路由所以当用户输入一个url时,路由器在firebase初始化之前被调用没有用户
-
@AaronSaunders 我有一个 database.js 文件,我的配置对象所在的位置。
app = firebase.initializeApp(confg)发生在这个文件中,db = app.database();被导出。main.js中未调用 database.js -
firebase.initializeApp(confg)不解析当前用户... -
@AaronSaunders 感谢您的回复。我需要澄清你所说的“解决”当前用户的意思,或者更确切地说,如何在
router.beforeEach回调中提供调用firebase.auth().currentUser的能力main.js
标签: node.js firebase vue.js firebase-authentication vue-router