How to render an ejs template from express using fetch without submitting form?

Viewed 50

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.

1 Answers

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.

Related