Submit form data and display on ejs template engine page

Make form with ejs template engine

Create files in view

addUser.ejs

<form action="/submit-user" method="post">
<input type="text" placeholder="enter user name" name="name" />
<br /><br />
<input type="text" placeholder="enter user age" name="age" />
<br /><br />
<input type="text" placeholder="enter user email" name="email" />
<br /><br />
<button>Add User</button>
</form>

This form sends data using POST method to the route /submit-user.


submitUser.ejs

<h3>Name: <%= name %></h3>
<h3>age:<%= age %></h3>
<h3>Email:<%= email %></h3>


Make routes

Now, connect the frontend form and result page using routes in your Express server.

app.get("/add-user", (req, resp) => {
resp.render("addUser");
});

app.post("/submit-user", (req, resp) => {
console.log(req.body);
resp.render("submitUser", req.body);
});

app.get loads the form

app.post receives form data and sends it to the template


Get Submitted data

Use req.body to receive the data that the user submitted via the form.

Important: To make this work, we must add this middleware:

app.use(express.urlencoded({ extended: false }));


Display submitted on ejs template page

In submitUser.ejs, we already used EJS tags to display values:

<h3>Name: <%= name %></h3>
<h3>age:<%= age %></h3>
<h3>Email:<%= email %></h3>

These values come from the req.body we passed in the POST route.