Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda