window.location.href 添加到现有主机名的链接而不是替换它

问题描述 投票:0回答:2

我有一个 POST API 函数,它在单击按钮时激活。

API 以字符串格式(“数据”变量)返回生成的链接,但是当我尝试在 in window.location.href = data 中输入时,该链接并没有替换实际的 href,而是在之后将其粘贴主机名。

所以基本上,我被重定向到 https://mywebsitedomain.com/"https://returnedurl.com",当然,404 页错误会发生。相反,我应该立即重定向到 https://returnedurl.com

关于它发生的原因有什么提示或见解吗?

buyCreditsBtn.addEventListener("click", async () => {
  const url = "https://endpoint.url";
  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      line_items: [
        {
          price: "price_product_x

",
          quantity: "1",
        },
      ],
      user_id: globalMemberId,
    }),
  };

  try {
    const response = await fetch(url, requestOptions);
    const data = await response.text();
    //console.log(data);
    window.location.href = data; // redirect to the returned URL
  } catch (error) {
    console.error("Error:", error);
  }
});

因此,为了验证“数据”变量是否正确,我没有直接将其放入 window.location.href,而是将其打印到控制台,将其另存为新变量并手动运行命令 window.location.href = data,并且效果很好。

我无法理解为什么 POST 函数不能那样工作。

javascript html api rest window.location
2个回答
0
投票

所以基本上,我被重定向到https://mywebsitedomain.com/"https://returnedurl.com",

HTTP 响应由包裹在

"
字符中的 URL 组成(您可以分辨出来,因为它们在您引用的 URL 中可见!)。

因为它以

"
开头,所以它被视为相对路径而不是绝对 URL。

引号可能是因为服务器正在响应 JSON 而不是纯文本。

读取正文并使用

json()
方法而不是
text()
方法从 JSON 中解析它。


-1
投票

URL 没有被替换,而是被附加到现有的主机名,因为“数据”变量中生成的 URL 很可能包括协议(http:// 或 https://)和域名(returnedurl.com)目标网站。

要解决此问题,您需要从“数据”变量中提取实际 URL 并将其设置为 window.location.href 的值。您可以通过使用正则表达式来匹配“数据”变量中的协议和域名并提取 URL 的剩余部分来完成此操作。

var data = "https://returnedurl.com";
var match = data.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
if (match) {
  window.location.href = data.replace(match[0], '');
} else {
  window.location.href = data;
}

© www.soinside.com 2019 - 2024. All rights reserved.