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

241
Vistas
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 Respuestas
Responde la pregunta

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 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