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

240
Visualizações
How to render an ejs template from express using fetch without submitting form?

login.js file:

const form  = document.getElementById('loginForm');

form.addEventListener('submit',async(e)=>{

     e.preventDefault();

   
    return await fetch(`localhost:8000/route`, {
      method: "get",
      headers: {
        "Content-Type": "application/json",
      },
    });
  

}

app.js file:

   app.get('/index',(req,res)=>{
        res.render('route.ejs');
    })

I only get the rendered html as a response but can't render it.I know that using form submission works.But can anyone plz tell me how to render the page without submitting form?Thank you in Advance.

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

0

The reason you get HTML as a response and not rendered because you use an AJAX call when using fetch. It doesn't instruct the browser what to do with that response.

You have few options.

Either when you get the response back you handle it in your callback like so:

return await fetch(`localhost:8000/route`, {
      method: "get",
      headers: {
        "Content-Type": "application/json",
      },
    }).then(res=> {
       let htmlText = await response.text();
       document.getElementsByTagName('body')[0].innerHTML(bodyContent);
    });

Or in fact if you just want to load a new page from your ejs template, set the window to the new location and browser will automatically render the response. Something like so in your login.js:

document.location.href = "/route_that_returns_html";

Note that since your question is generic you can take one of the above approach. However as your code suggests if you are trying to implement a login then the right way to do it is in following steps:

  1. Let the form submit as usual ( not using ajax/fetch)
  2. On server side using express, execute the login routine to authenticate the user.
  3. If the authentication passes issue a res.redirect() to the authenticated page that renders using ejs or if fails, redirect back to login page with error.

Finally this DigitalOcean Article explains how to use ejs properly and is worth a read.

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