Nuxt 无法使用中间件自动重定向(受保护的路由)
我正在尝试设置当用户未经身份验证时从受保护资源自动重定向到登录页面。
当我从 nuxt 实现示例重定向时,我得到了他的错误:
Error: Redirected when going from "/" to "/login" via a navigation guard.
at createRouterError (vue-router.esm.js?8c4f:2065:1)
at createNavigationRedirectedError (vue-router.esm.js?8c4f:2024:1)
at eval (vue-router.esm.js?8c4f:2376:1)
at Vue._next (client.js?06a0:299:1)
at app.context.redirect (utils.js?ebed:235:1)
at eval (auth.js?14c2:8:1)
at promisify (utils.js?ebed:314:1)
at middlewareSeries (utils.js?ebed:291:1)
at Vue.callMiddleware (client.js?06a0:264:1)
at Vue._callee6$ (client.js?06a0:267:1)
它似乎也在某种程度上锁定了 chrome 浏览器。
这是我的实现。
〜/middleware/auth.js
export default function ({ store, redirect }) {
if (process.client && !store.getters["isLoggedIn"]) return redirect("/login");
}
〜/nuxt.config.js
export default {
// ..
middleware: ["auth"],
// ..
};
〜/src/pages/protected.vue
<script>
export default {
middleware: "auth",
};
</script>
I'm trying to set up a automatic redirects from protected resources to login pages when the user is not authenticated.
When I implement the example redirect from nuxt I get his error:
Error: Redirected when going from "/" to "/login" via a navigation guard.
at createRouterError (vue-router.esm.js?8c4f:2065:1)
at createNavigationRedirectedError (vue-router.esm.js?8c4f:2024:1)
at eval (vue-router.esm.js?8c4f:2376:1)
at Vue._next (client.js?06a0:299:1)
at app.context.redirect (utils.js?ebed:235:1)
at eval (auth.js?14c2:8:1)
at promisify (utils.js?ebed:314:1)
at middlewareSeries (utils.js?ebed:291:1)
at Vue.callMiddleware (client.js?06a0:264:1)
at Vue._callee6$ (client.js?06a0:267:1)
It also seems to somewhat lock up the chrome browser.
Here's my implementation.
~/middleware/auth.js
export default function ({ store, redirect }) {
if (process.client && !store.getters["isLoggedIn"]) return redirect("/login");
}
~/nuxt.config.js
export default {
// ..
middleware: ["auth"],
// ..
};
~/src/pages/protected.vue
<script>
export default {
middleware: "auth",
};
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您共享的代码,我可能不清楚,但是 nuxt.config.js 中定义的中间件需要是 router 对象的子级。所以:
还值得一提的是,如果您的项目中包含 标准身份验证模块,它会使用具有相同名称的相同中间件实现,因此您可能需要小心使用“auth”作为此处的文件名。
It may just be unclear to me based on the code you've shared, but the middleware defined within
nuxt.config.js
needs to be a child of therouter
object. So:Also may be worth mentioning, if you have the standard auth module included in your project, it uses the same middleware implementation with the same name, so you may want to be careful using "auth" as your filename here.