gpt4 book ai didi

javascript - 在查询字符串中获取重定向 uri 的子部分

转载 作者:行者123 更新时间:2023-11-30 11:43:45 25 4
gpt4 key购买 nike

所以我有一个看起来像这样的 URL:

localhost:9031?redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fcallback&scope=test

我想重定向到 URL localhost:8080/something,它使用了部分重定向 uri 但从中删除了 /callback

为了获得重定向 uri,我有一个方法执行以下操作,并将字符串 redirect_uri 传递给它:

function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
}

这会返回字符串 http://localhost:8080/callback。然后要获取 callback 的索引,我使用以下函数。

function getPosition(string, subString, index) {
return string.split(subString, index).join(subString).length;
}

然后当点击按钮时,我将它们放在一起并执行:

$('.button').click(function(e) {
var query = window.location.search.slice(1);
var redirect = getQueryVariable('redirect_uri');
var index = getPosition(redirect, '/', 3);
var baseUrl = redirect.slice(0, index);
window.location.href = baseUrl + '/something';
});

这一切都按预期工作,但似乎并不是特别安全或高效。寻找使用我不知道的 JavaScript 或 JQuery 功能的优化或建议。希望避免使用第 3 方库,但如果它们足够好,我肯定仍会使用它们。

最佳答案

我建议让浏览器完成解析 URL 的繁重工作。假设您有来自查询字符串的解码重定向 URI,您可以执行以下操作:

var myUrl = 'http://localhost:8080/callback&scope=test';

function parseURL(url) {
var a = document.createElement("a");
a.href = url;

return {
protocol: a.protocol,
hostname: a.hostname,
port: a.port,
pathname: a.pathname
};
}

var parsedURL = parseURL(myUrl);
console.log(parsedURL.protocol + '//' + parsedURL.hostname + ':' + parsedURL.port + '/something');

您可以根据结果构建基本 url,并在必要时选择性地解析路径名。

关于javascript - 在查询字符串中获取重定向 uri 的子部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41705423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com