我正在尝试在 Vue 项目中实现 Oauth(使用 Github(,当我的回调 url 从 github 调用时,它会将查询字符串附加到 url 的哈希之前?code=something
。
例如,如果我在浏览器中加载https://myapp.com
并单击我的登录链接<a href="https://github.com/login/oauth/authorize?scope=user:email&client_id=1234j1234jk&redirect_uri=https://myapp.com/#/something">Login</a>
我会被重定向到https://myapp.com/?code=asdfasdf#/something
这意味着this.$route.query
为空。
作为 Vue 和 Oauth 的新手,我如何解决这个问题,以便在调用我的回调时它会转到https://myapp.com/#/something?code=asdfadsf
以便this.$route.query
包含代码?
Github 可能因为#
而把事情搞砸了。作为一种解决方法,您可以使 Github 重定向到另一个端点,例如www.yourhost.com/api/v1/redirect-to-home?code=ABCDE
(其中没有#
(,然后您可以正确重定向到 https://myapp.com/#/something?code=ABCDE
。
Github 在这里做正确的事情,因为 OAuth 处理 url 的查询部分,并且不会更改锚点。
您可以做的是在启动过程中检测并手动调整 url,这可以按如下方式完成:
在你的主引导程序.js(你在其中new Vue
的文件(文件中,你可以在 Vue 加载之前手动检测这个锚点并更新路径。
这可以通过检查引导程序中的window.location
,然后调用window.location.href.replace
来替换没有可见重定向的 url:
// getParameterByName from https://stackoverflow.com/a/901144/1542723
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[[]]/g, "\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/+/g, " "));
}
const code = getParameterByName('code');
if(code) {
const l = window.location;
window.location.replace(l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') + l.pathname + '123#' + l.hash + '?code=' + code);
}