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

156
Visualizações
Send POST request from front-end javascript to back-end node.js

In the front-end script, I have a code like this to create the POST request to the server.

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/visitor/detect/1", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify({
        value: "test"
    }));

Then here is my route in my server

router.post('/visitor/detect/1', (req, res) => {
      console.log(req.body);
      res.redirect('/visitor/login');
});

I'm expecting to redirect the page to /visitor/login after a successful post request, but it didn't. However, it is displaying the req.body.

What is the problem, and what way can I do to successfully send the post request from the front-end and redirect the page to the back-end?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You cannot redirect with the ajax request the way you are trying to do it. Here is an snippet that does what I think you are trying to do. You might also look into the fetch api instead of using XMLHttpRequest.

On the server:

app.post("/visitor/detect/1", (req, res) => {
  console.log(req.body);
  res.json({ redirectRoute: "/visitor/login" });
});

Client side:

  var xhr = new XMLHttpRequest();
    xhr.open("POST", "/visitor/detect/1", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify({
        value: "test"
    }));

    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            var jsonResponse = JSON.parse(xhr.responseText)
            window.location.replace(jsonResponse.redirectRoute)
        }
    }
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