In this tutorial, we will learn how to handle simple form submissions using Express and EJS. This is a straightforward example that demonstrates the basics of handling forms in a web application with the power of EJS templating.
Step 1: Set up EJS
To get started, we need to install the ejs package, which will allow us to render dynamic views. Install it by running the following command:
npm install ejs
Step 2: Set up the Express Server
Next, we will create a new file named server.js
to set up the Express server. In this step, we will configure Express to use EJS as the view engine and also set up the necessary middleware for form data handling. Here’s the code to set up your server:
server.js
const express = require('express'); const app = express(); const port = 3000; app.set('view engine', 'ejs'); app.use(express.urlencoded({ extended: true })); // Route to render the form app.get('/', (req, res) => { res.render('form'); }); // Route to handle form submission app.post('/submit', (req, res) => { const name = req.body.name; res.send(`Hello, ${name}!`); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
This sets up two routes:
- A GET route to render the form.
- A POST route to handle form submissions and display the result.
Step 3: Create the EJS View
Now, create a folder named views
in the project directory, and inside that folder, create a file named form.ejs
This is where we define the HTML form that users will fill out. The form submits the user’s name to the server.
form.ejs (views/form.ejs)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Form Handling</title> </head> <body> <form action="/submit" method="POST"> <input type="text" name="name" placeholder="Enter your name" required> <button type="submit">Submit</button> </form> </body> </html>
Step 4: Running the Server
Now that the form and server are set up, run the server using the following command:
When you visit http://localhost:3000
in your browser, you should see the form. Once you fill in your name and submit the form, you will be greeted with a message saying “Hello, [Your Name]!”.
Expected Output
1. Form View
2. Output After Submission
output after submit drive link
Conclusion
Handling form submissions with Express and EJS is a simple but powerful technique for creating interactive web applications. With these tools, you can easily manage dynamic content rendering and handle user inputs efficiently. This example just scratches the surface, and you can build more complex forms and workflows with additional validation, styling, and data processing.