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.
data
?