我在从应用程序内使用的API创建指向URL的重定向时遇到问题。我请求在重定向URL中使用session token
,但是当令牌中包含+
时遇到问题。我的猜测是浏览器将其作为space
,而不是实际的令牌字符,这经常导致重定向失败。
这里是一个示例令牌,可以从请求返回到API:1w5OX65MRj+3J9R5AXjMWQLAAXIo5TXa
查看“网络”标签,我看到它尝试使用此令牌请求重定向:1w5OX65MRj 3J9R5AXjMWQLAAXIo5TXa
,这就是它引起问题的原因。
[我尝试用+
替换%2B
,但似乎我的应用程序根本没有替换它,这对我来说有点奇怪。
这是我的代码:
let token = "";
$.get('/_token_req', {contentType: "application/x-www-form-urlencoded"}, (response) => {
//console.log(response);
token = response;
token = token.replace(/\+/g, "%2B"); // this doesn't replace the + character for some reason
$.get('/_redirect', {token: response}, (response) => {
//console.log(response);
if(response == "OK"){
window.location.href = "https://someapi/payments/?auth_token=" + token;
}
})
})
我对URL编码了解不多,但是如果有人可以向我指出正确的方向,那将非常有帮助。谢谢!
您的代码有2个问题:
您需要使用encodeURIComponent
来编码令牌中的任何符号,以便可以以适当的方式发送它。
两个,在调用第二个请求$.get('/_redirect'
时,您没有使用replace
d令牌,而是从先前的请求中收到的简单的response
。
将您的代码更改为此,以消除这两个错误:
let token = "";
$.get('/_token_req', {contentType: "application/x-www-form-urlencoded"}, (response) => {
token = encodeURIComponent(response);
$.get('/_redirect', {token: token}, (response) => {
if(response == "OK"){
window.location.href = "https://someapi/payments/?auth_token=" + token;
}
})
})