I have a button that when clicked, is initiating a POST request to my API. I then want to take the response URL from the API call and redirect to it.
This is what my JS look like:
function submitPassowrd(url) {
let xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();
let u = xhr.responseText
if (xhr.status === 200) {
window.location.replace(u);
return false
}
return false
}
The problem is, that instead of redirecting to the URL from the API response, it is concatenating it to the base URL. So if the URL is http://example.com, it will just add it like: http://127.0.0.1:8081/http://example.com.
That said, when I am using a hard-coded URL, it works just fine and redirects me properly to the website provided in window.location.replace. For example:
function submitPassowrd(url) {
let password = document.getElementById('password').value;
let xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify();
let u = xhr.responseText
if (xhr.status === 200) {
window.location.replace('http://example.com'); // <<<<<<< hard-coded URL
return false
}
return false
}
Also, I tried using window.location.href which caused the exact same behavior.
What can explain this behavior?
You should use window.location.href or simply window.location instead of window.location.replace for this use case imho.
That been said, the possible explanation for .replace behavior is that the url is encoded and thus not perceived as a url (rather a string only) and thus gets concatenated to the current page url. You can console.log the output of u to see if the returned string is encoded?