Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading