处理Vue Router(历史模式)和Webpack外部重定向
P粉681400307
P粉681400307 2023-08-28 12:13:17
[Vue.js讨论组]
<p>SO社区,</p> <p>我正在尝试在现有的Vue 2应用程序中添加外部身份验证。我遇到的问题是,当外部IdP重定向回Vue应用程序并带有路径<code>/redirect</code>时,Vue Router似乎不会遵守更新后的路径并路由到正确的组件。换句话说,Vue Router会将路由到<code>/</code>组件而不是<code>/redirect</code>组件。</p> <p>Vue Router设置了<code>mode: 'history'</code>和Webpack设置了<code>historyApiFallback: true,</code>。</p> <h1>当前行为:</h1> <ol> <li>用户导航到<code>https://localhost:8080/</code>并呈现<code>Login</code>组件。</li> <li>用户输入其ID并被重定向到外部IdP。</li> <li>成功验证后,IdP返回到指定的重定向URL:<code>https://localhost:8080/redirect</code></li> <li>由于历史模式,Webpack将浏览器发送到<code>/</code>,从而返回到<code>Login</code>组件。</li> <li>在<code>Login</code>组件中,<code>mounted()</code>钩子检查<code>if (window.location.pathname === '/redirect') router.push({ path: '/redirect' });</code></li> <li>Vue Router转到<code>/</code>路径,而不是<code>/redirect</code>和其组件。</li> </ol> <h2>技术细节:</h2> <p>Vue - 2.5.15</p><p> 路由器视图 - 3.0.0</p><p> Webpack - 4.17.1</p><p> Webpack 开发服务器 - 3.1.4</p> <h2><code>webpack.dev.js</code></h2> <pre class="brush:php;toolbar:false;">devServer: { historyApiFallback: true,</pre> <h2><code>router.js</code></h2> <pre class="brush:php;toolbar:false;">const router = new VueRouter({ mode: 'history', routes: [ ... { path: '/redirect', component: Redirect, }, { path: '/', redirect: () =&gt; { }, ... router.beforeEach((to, from, next) =&gt; { const user = store.state.user.authorizedUser const toPath = to.path if (toPath === '/redirect') return });</pre> <h2><code>App.vue</code></h2> <pre class="brush:php;toolbar:false;">new Vue({ el: '#login', render: h =&gt; h(Login), store, })</pre> <h2><code>登录.vue</code></h2> <pre class="brush:php;toolbar:false;">mounted() { if (window.location.pathname === '/redirect') router.push({ path: '/redirect' }); }</pre> <p>请告诉我是否需要提供任何其他细节或代码。提前感谢您的帮助。</p>
P粉681400307
P粉681400307

全部回复(1)
P粉208469050

所以,问题似乎出现在顶层组件 Login 在路由器启动之前充当交通警察的角色。我不得不编辑 Login 组件以手动挂载 Redirect 组件。

我不建议这种设置方式。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号