Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!