Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
window.location.replace unexpected behaviour

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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?

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda