Contents

Introduction to Express.js

Express.js is a minimal and flexible web application framework for Node.js, providing a robust set of features to develop web and mobile applications. It simplifies the process of building server-side logic and handling HTTP requests and responses, making it easier to build web applications, RESTful APIs, and more. Express.js is built on top of Node.js, providing additional functionality and simplifying tasks such as routing, middleware management, and handling HTTP requests.

Setting Up Express.js in a Node.js Project

To start using Express.js in your Node.js project, you first need to install it and set up your project.

Step 1: Initialize a Node.js Project

If you haven’t already initialized a Node.js project, you can do so by running the following command:

				
					npm init -y





				
			

This command creates a package.json file in your project directory, which tracks your project’s dependencies and settings.

Step 2: Install Express.js

Next, install Express.js as a dependency in your project:

				
					npm install express






				
			

This command installs Express.js and adds it to the dependencies section of your package.json file.

Step 3: Create an Express Server

Create a new file named app.js (or index.js) and set up a basic Express server:

				
					const express = require('express');
const app = express();

const PORT = 3000;

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});







				
			

Explanation:

  • express(): Creates an Express application.
  • app.get(): Defines a route that handles GET requests to the root URL (/). When this route is accessed, the server responds with “Hello, World!”.
  • app.listen(): Starts the server and listens on the specified port (3000 in this case).

Step 4: Run the Express Server

To start the server, run the following command in your terminal:

				
					node app.js



				
			

Open your browser and go to http://localhost:3000. You should see “Hello, World!” displayed on the page.

Creating Routes and Handling Requests with Express

Express simplifies the process of creating routes and handling HTTP requests. Routes define the endpoints of your web application and specify how the application responds to client requests.

Example: Creating Basic Routes

				
					const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Welcome to the home page!');
});

app.get('/about', (req, res) => {
  res.send('This is the about page.');
});

app.post('/contact', (req, res) => {
  res.send('Contact form submitted.');
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});





				
			

Explanation:

  • app.get('/about', ...): Handles GET requests to the /about route.
  • app.post('/contact', ...): Handles POST requests to the /contact route.
  • Route Parameters: You can define dynamic routes with route parameters. For example, app.get('/users/:id', ...) would match /users/1, /users/2, etc.

Example: Handling Route Parameters

				
					app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`User ID: ${userId}`);
});






				
			

Middleware in Express: What It Is and How to Use It

Middleware in Express is a function that executes during the lifecycle of a request to the server. It has access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware functions can perform various tasks, such as logging, authentication, parsing request bodies, and more.

Example: Using Middleware for Logging

				
					const express = require('express');
const app = express();

// Middleware function for logging
app.use((req, res, next) => {
  console.log(`${req.method} request for '${req.url}'`);
  next(); // Pass control to the next middleware function
});

app.get('/', (req, res) => {
  res.send('Welcome to the home page!');
});

app.get('/about', (req, res) => {
  res.send('This is the about page.');
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});




				
			

Explanation:

  • app.use(): This method is used to apply middleware to all routes. The middleware function logs the HTTP method and URL of each incoming request.
  • next(): The next function allows you to pass control to the next middleware function. If you don’t call next(), the request will hang and not proceed to the next middleware or route handler.

Common Types of Middleware:

  1. Application-Level Middleware: Applied to the entire app using app.use().
  2. Route-Level Middleware: Applied to specific routes using app.get('/route', middlewareFunction, handlerFunction).
  3. Error-Handling Middleware: Used to catch and handle errors. It typically has four arguments: (err, req, res, next).

Serving Static Files and Templates with Express

Express can serve static files like HTML, CSS, and JavaScript, as well as render dynamic templates using a template engine.

Serving Static Files

To serve static files, you use the express.static middleware.

Example: Serving Static Files

				
					const express = require('express');
const path = require('path');
const app = express();

// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
  res.send('Home page');
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});





				
			

Explanation:

  • express.static(): Serves static files from the specified directory (public in this case). If a file like style.css is in the public directory, it can be accessed via http://localhost:3000/style.css.

Serving Dynamic Templates with a Template Engine

Express supports various template engines like EJS, Pug, and Handlebars. These engines allow you to render dynamic HTML pages by passing data to the templates.

Example: Setting Up EJS as a Template Engine

  • 1.  Install EJS:
				
					npm install ejs




				
			
  • 2.       Set EJS as the View Engine:
				
					const express = require('express');
const app = express();

// Set the view engine to EJS
app.set('view engine', 'ejs');

// Define a route that renders an EJS template
app.get('/', (req, res) => {
  res.render('index', { title: 'Home', message: 'Welcome to the Home Page!' });
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});





				
			
  • 3.  Create an EJS Template:

Create a views directory in your project root, and then create an index.ejs file inside it:

				
					<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
</head>
<body>
  <h1><%= message %></h1>
</body>
</html>






				
			

Explanation:

  • app.set('view engine', 'ejs'): Configures EJS as the template engine for the application.
  • res.render('index', { title: 'Home', message: 'Welcome to the Home Page!' }): Renders the index.ejs template, passing title and message as data that the template can use.

Conclusion

Express.js is a powerful and flexible framework that simplifies the process of building web applications with Node.js. By setting up Express, creating routes, handling requests, and using middleware, you can build robust server-side applications. Additionally, Express makes it easy to serve static files and render dynamic templates, enabling you to create both simple websites and complex web applications. As you become more familiar with Express, you’ll find it to be an indispensable tool in your Node.js development toolkit.