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

379
Visualizações
How to redirect user to different web page using Express.js? (Yes, I have tried using the `redirect` method)

I am creating a simple web application with no front-end framework (other than jQuery) with an Express.js backend. I am trying to redirect the user to a different page once a registration form is submitted, but instead of loading the other page, the page's HTML code is just printed to the console... It would be easier to show you:

Front-end script that handles the form submission

$("#registration-form").on("submit", event => {
  const formData = convertFormToJson($("#registration-form"));

  $.ajax({
    type: "POST",
    url: "api/auth/registration",
    data: JSON.stringify(formData),
    contentType: "application/json;charset=UTF-8",
    success: function(data) {
      console.log(data); // This is where the HTML code is being printed
    },
    error: function(request, status, error) {
      console.log(error);
    }
  });

  event.preventDefault();
});

My backend index.js

app.post("/api/auth/registration", (req, res) => {
  const { email, password, confirmPassword } = req.body;
  
  // Authenticate credentials... 

  res.redirect("/login");
  
});

app.get("/registration", (req, res) => {
  console.log('registration');
  res.sendFile(__dirname + "/registration.html");
});

app.get("/login", (req, res) => {
  console.log("login");
  res.sendFile(__dirname + "/login.html");
})

So I use res.redirect("/login"); which correctly calls the express route, "/login". But instead of the browser displaying the login page, the page's code is printed to the console by the console.log(data) method call in the success method of the ajax call. Any ideas why this would be happening?

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

0

Thanks to @Phil, I found an answer to a related question that happened to explain why I was having this problem. This is a quote from the referenced answer: There are multiple ways to submit a form from the browser:

  1. HTML form, submit button, user presses submit button, no Javascript involved.
  2. HTML form in the page, Javascript gets DOM element for the form and calls .submit() method on the form object.
  3. Ajax call using the XMLHttpRequest interface with the POST method and manually sending appropriate form data.
  4. Ajax Fetch call with the POST method and manually sending appropriate form data. With #1 or #2, the browser sends the form and the browser will pay attention to redirects and will display the form response (whether redirected or not) in the browser.

With #3 and #4, the form is sent via Javascript and the response comes back to your Javascript. #3 does not process redirects. #4 has an option to process redirects. Here's more info on each of the above options. #3 and #4 do not affect the browser display is not affected at all unless you program your own Javascript to process the request and affect the browser display (either by inserting content or setting window.location to a new URL.

Because I was making an ajax fetch call instead of letting the HTML form handle its own submit, the browser was not responding to the redirect.

The fix: I simply took out the jQuery ajax method and included the method and action tags in the form, resulting in the form submitting directly to the server.

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