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.
2
Answers
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 thetext()
method.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.