javascripthtmlapirestwindow.location

window.location.href adding link to an existing hostname instead of replacing it


I have a POST API function which activates on a button click.

The API returns a generated link in a string format ('data' variable), but when I try to put in in window.location.href = data, the link is not replacing an actual href, but just glues it after the hostname.

So basically, I get redirected to https://mywebsitedomain.com/"https://returnedurl.com", and of course, 404-page error happens. Instead, I should get redirected to https://returnedurl.com straight away.

Any tips or insights on why it happened?

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);
  }
});

So to verify if 'data' variable is correct, instead of putting it straight to window.location.href I printed it out to a console, saved it as a new variable and ran a command window.location.href = data manually, and it worked perfectly.

I cannot wrap my head around why the POST function doesn't work like that.


Solution

  • So basically, I get redirected to https://mywebsitedomain.com/"https://returnedurl.com",

    The HTTP response consists of a URL wrapped in " characters (you can tell because they are visible in the URL you quoted!).

    Since it starts with a " it is treated as a relative path and not an absolute URL.

    Likely the quotes are because the server is responding with JSON and not plain text.

    Read the body and parse it from JSON using the json() method instead of the text() method.