Handling Form Data
EJS can also be used to render forms and handle form submissions. Here’s a simple example:
Update index.js to Handle Form Submission:
Use body-parser to handle form data (body-parser is a Middleware).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Form</title>
</head>
<body>
<form action="/submit" method="POST">
<input type="text"
name="username"
placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<% if (message) { %>
<p><%= message %></p>
<% } %>
</body>
</html>
import express from "express";
import bodyParser from "body-parser";
const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.render("index.ejs", {
message:""
});
});
app.post("/submit", (req,res) =>{
const userName = req.body['username'];
res.render("index.ejs",{
message:`Hello from ${userName}!`
});
});
app.listen(port, ()=>{
console.log(`Listening to port ${port}.`);
});
Output:
Passing Data to EJS Templates
EJS (Embedded JavaScript) is a simple templating language that lets you induce HTML language with plain JavaScript. It’s especially popular in Node.js operations for rendering dynamic web runners. It is used to dynamically render HTML pages on the server side. This article will give a detailed companion on how to pass data to EJS templates.