While Node.js provides the core functionality to create HTTP servers, Express.js is a minimalist and flexible web framework built on top of Node.js that makes it easier to build robust and scalable web applications. In this module, we’ll explore how to use Express.js to create a simple web application with routing, middleware, and dynamic content.
Table of Contents
- Introduction to Express.js
- Setting Up an Express.js Project
- Creating Routes in Express.js
- Using Middleware in Express.js
- Handling Form Data in Express.js
- Sending JSON Responses
- Dynamic Content with Templates (Using EJS)
- Error Handling in Express.js
- Conclusion
1. Introduction to Express.js
Express.js is one of the most popular web frameworks for Node.js. It simplifies the process of handling HTTP requests, managing routes, and rendering views. Express is lightweight, fast, and can be easily integrated with other Node.js libraries and tools.
To use Express, you must first install it in your project using npm
:
bashCopyEditnpm install express
2. Setting Up an Express.js Project
Start by creating a basic Express app. First, create a new directory for your project, then initialize a Node.js project:
mkdir express-app
cd express-app
npm init -y
Next, install Express:
npm install express
Now, create an app.js
file and add the following code to create your first Express server:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
To start the server, run:
node app.js
Visit http://localhost:3000
in your browser to see the response.
3. Creating Routes in Express.js
Routes define how your application handles incoming requests to different endpoints. In Express, you can create routes for different HTTP methods like GET
, POST
, PUT
, and DELETE
.
app.get('/about', (req, res) => {
res.send('This is the About page');
});
app.post('/submit', (req, res) => {
res.send('Form submitted');
});
You can also capture URL parameters using :parameter_name
:
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
4. Using Middleware in Express.js
Middleware functions are functions that have access to the request (req
), response (res
), and the next middleware function in the application’s request-response cycle. Express.js provides built-in middleware for tasks like logging, parsing request bodies, and handling errors.
// Built-in middleware to serve static files
app.use(express.static('public'));
// Custom middleware to log request details
app.use((req, res, next) => {
console.log(`Request made to: ${req.url}`);
next();
});
5. Handling Form Data in Express.js
Express makes it easy to handle form submissions. You can use express.urlencoded()
to parse data sent from HTML forms with application/x-www-form-urlencoded
encoding.
app.use(express.urlencoded({ extended: true }));
app.post('/submit', (req, res) => {
const { name, age } = req.body;
res.send(`Received name: ${name}, age: ${age}`);
});
This setup allows your application to handle form submissions easily.
6. Sending JSON Responses
One of the common tasks in API development is sending JSON responses. Express makes this simple with the res.json()
method:
app.get('/data', (req, res) => {
const responseData = { message: 'This is some data', status: 'success' };
res.json(responseData);
});
This sends the data as a JSON object, making it suitable for API responses.
7. Dynamic Content with Templates (Using EJS)
For dynamic HTML content, you can use template engines like EJS, Pug, or Handlebars. In this example, we’ll use EJS.
Install EJS:
npm install ejs
Set up Express to use EJS as the template engine:
app.set('view engine', 'ejs');
app.set('views', './views'); // Path for views
Now, create an index.ejs
file inside the views
folder:
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content</title>
</head>
<body>
<h1>Hello, <%= name %>!</h1>
</body>
</html>
Then, render the EJS template in your route:
app.get('/greet/:name', (req, res) => {
res.render('index', { name: req.params.name });
});
Now, visiting http://localhost:3000/greet/John
will render Hello, John!
.
8. Error Handling in Express.js
Error handling is essential for a robust web application. Express allows you to define custom error-handling middleware.
app.use((req, res, next) => {
const err = new Error('Page not found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({ message: err.message });
});
This handles any errors that occur in the application and sends an appropriate response to the client.
9. Conclusion
Express.js simplifies building web applications by providing a set of powerful features, including routing, middleware, and support for templates. With Express, you can easily manage HTTP requests, handle form submissions, send JSON responses, and much more.
By mastering Express, you’re on your way to building robust web applications that scale. Stay tuned for the next module:
“Connecting a Node.js Application to a Database (Using MongoDB)”