1

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.

1
  • 1
    What is the value of data? Feb 19 at 18:20

2 Answers 2

1

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.

2
  • Haha, it worked like a charm! Thank you! Indeed that was a problem because the 'data' was returned like a string. Even chat-GPT didn't manage to solve this one, haha!
    – Rox AS
    Feb 19 at 18:29
  • ChatGPT is a BS generator. I'm surprised when it manages to churn out a correct answer.
    – Quentin
    Feb 19 at 18:31
-1

The URL is not getting replaced and is being appended to the existing hostname because the generated URL in the 'data' variable most likely includes the protocol (http:// or https://) and domain name (returnedurl.com) of the target website.

To fix this, you need to extract the actual URL from the 'data' variable and set it as the value of window.location.href. You can do this by using a regular expression to match the protocol and domain name in the 'data' variable and extracting the remaining part of the 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;
}

1
  • "because the generated URL in the 'data' variable most likely includes the protocol (http:// or https://)" — The problem is almost the opposite of this.
    – Quentin
    Feb 19 at 18:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.