Express.js Framework

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It facilitates the rapid development of Node-based web applications by providing a simple and straightforward API. This chapter will cover the basics to advanced usage of Express.js, providing detailed explanations and examples to ensure a comprehensive understanding.

What is Express.js?

Express.js is a web application framework for Node.js, designed for building single-page, multi-page, and hybrid web applications. It’s the backend part of the popular MEAN (MongoDB, Express, Angular, Node) stack.

Why use Express.js?

  • Simplicity: Express provides a thin layer of fundamental web application features, without obscuring Node.js features.
  • Flexibility: Allows for a lot of flexibility in how you structure your application.
  • Middleware: Has a robust set of HTTP utility methods and middleware for creating APIs.
  • Community: Large community and extensive middleware packages available via npm.

Setting Up Express.js

Installation

To install Express.js, you need to have Node.js and npm (Node Package Manager) installed. You can then create a new project and install Express:

				
					mkdir express-app
cd express-app
npm init -y
npm install express

				
			

Basic Express Server

Create a file named app.js and add the following code to set up a basic Express server:

File: app.js

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

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

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

				
			

Explanation:

  • const express = require('express');: Imports the Express module.
  • const app = express();: Creates an Express application.
  • app.get('/', callback): Defines a route handler for the root URL (/).
  • res.send('Hello, Express!'): Sends a response back to the client.
  • app.listen(port, callback): Starts the server and listens on the specified port.

Output:

Running the script with node app.js starts the server. Visit http://localhost:3000 in your browser to see the “Hello, Express!” message.

Routing in Express.js

Routing refers to how an application’s endpoints (URIs) respond to client requests. Express provides a robust routing system that makes it easy to define routes.

Basic Routes

File: app.js

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

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

app.get('/about', (req, res) => {
    res.send('About Page');
});

app.get('/contact', (req, res) => {
    res.send('Contact Page');
});

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

				
			

Explanation:

  • app.get('/about', callback): Defines a route handler for /about.
  • app.get('/contact', callback): Defines a route handler for /contact.

Output:

  • Visiting http://localhost:3000 displays “Hello, Express!”.
  • Visiting http://localhost:3000/about displays “About Page”.
  • Visiting http://localhost:3000/contact displays “Contact Page”.

Route Parameters

Route parameters are named URL segments used to capture values specified at their position in the URL.

File: app.js

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

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

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

				
			

Explanation:

  • app.get('/user/:id', callback): Defines a route with a parameter id.
  • req.params.id: Accesses the id parameter from the URL.

Output:

Visiting http://localhost:3000/user/123 displays “User ID: 123”.

Query Parameters

Query parameters are used to filter data. They are appended to the URL after a ? symbol.

File: app.js

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

app.get('/search', (req, res) => {
    res.send(`Search Query: ${req.query.q}`);
});

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

				
			

Explanation:

  • app.get('/search', callback): Defines a route for search queries.
  • req.query.q: Accesses the q query parameter from the URL.

Output:

Visiting http://localhost:3000/search?q=nodejs displays “Search Query: nodejs”.

Middleware in Express.js

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware can perform the following tasks:

  • Execute any code.
  • Make changes to the request and response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

Application-Level Middleware

File: app.js

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

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

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

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

				
			

Explanation:

  • app.use(callback): Registers a middleware function that logs the request method and URL.
  • next(): Passes control to the next middleware function.

Output:

Running the script logs the request details to the console for every request.

Built-in Middleware

Express has several built-in middleware functions, including express.static to serve static files and express.json to parse JSON bodies.

File: app.js

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

// Middleware to serve static files
app.use(express.static(path.join(__dirname, 'public')));

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

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

				
			

Explanation:

  • express.static(path): Serves static files from the specified directory.

Output:

Creating a directory named public and placing a file named index.html in it will serve that file when visiting http://localhost:3000.

Handling Forms and File Uploads

Express can handle form submissions and file uploads using middleware such as body-parser and multer.

Handling Form Submissions

File: app.js

				
					const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

// Middleware to parse URL-encoded bodies
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/form', (req, res) => {
    res.send(`
        <form action="/submit" method="post">
            <input type="text" name="name" placeholder="Name" />
            <button type="submit">Submit</button>
        </form>
    `);
});

app.post('/submit', (req, res) => {
    res.send(`Form submitted! Name: ${req.body.name}`);
});

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

				
			

Explanation:

  • bodyParser.urlencoded(): Middleware to parse URL-encoded bodies.
  • req.body.name: Accesses the name field from the form submission.

Output:

Visiting http://localhost:3000/form displays a form. Submitting the form displays the submitted name.

Handling File Uploads

File: app.js

				
					const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const port = 3000;

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/');
    },
    filename: (req, file, cb) => {
        cb(null, `${Date.now()}-${file.originalname}`);
    }
});

const upload = multer({ storage: storage });

app.get('/upload', (req, res) => {
    res.send(`
        <form action="/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="file" />
            <button type="submit">Upload</button>
        </form>
    `);
});

app.post('/upload', upload.single('file'), (req, res) => {
    res.send(`File uploaded! ${req.file.filename}`);
});

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

				
			

Explanation:

  • multer.diskStorage(): Configures the storage engine for Multer.
  • upload.single('file'): Middleware to handle single file uploads.
  • req.file.filename: Accesses the uploaded file’s name.

Output:

Visiting http://localhost:3000/upload displays an upload form. Uploading a file displays the uploaded file’s name.

Using Templating Engines

Templating engines allow you to generate HTML dynamically based on your data. Express supports various templating engines like Pug, EJS, and Handlebars.

Using Pug

File: app.js

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

// Set Pug as the templating engine
app.set('view engine', 'pug');
app.set('views', './views');

app.get('/', (req, res) => {
    res.render('index', { title: 'Express', message: 'Hello, Pug!' });
});

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

				
			

File:views/index.pug

				
					doctype html
html
    head
        title= title
    body
        h1= message

				
			

Explanation:

  • app.set('view engine', 'pug'): Sets Pug as the templating engine.
  • app.set('views', './views'): Sets the directory for the views.
  • res.render(view, data): Renders the specified view with the provided data.

Output:

Visiting http://localhost:3000 displays “Hello, Pug!”.

Error Handling

Error handling middleware is used to catch and process errors that occur during request handling.

File: app.js

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

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

// Middleware to handle 404 errors
app.use((req, res, next) => {
    res.status(404).send('Page not found');
});

// Error handling middleware
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

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

				
			

Explanation:

  • app.use((req, res, next)): Middleware to handle 404 errors.
  • app.use((err, req, res, next)): Error handling middleware to catch and process errors.

Output:

Visiting a non-existent route displays “Page not found”. Errors are logged and a 500 error is sent to the client.

Building a RESTful API

Express is widely used for building RESTful APIs. Here, we’ll create a simple API to manage a list of users.

File: app.js

				
					const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

app.use(bodyParser.json());

let users = [];

// Get all users
app.get('/users', (req, res) => {
    res.json(users);
});

// Create a new user
app.post('/users', (req, res) => {
    const user = req.body;
    users.push(user);
    res.status(201).json(user);
});

// Get a user by ID
app.get('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) {
        return res.status(404).send('User not found');
    }
    res.json(user);
});

// Update a user by ID
app.put('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) {
        return res.status(404).send('User not found');
    }
    Object.assign(user, req.body);
    res.json(user);
});

// Delete a user by ID
app.delete('/users/:id', (req, res) => {
    const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
    if (userIndex === -1) {
        return res.status(404).send('User not found');
    }
    users.splice(userIndex, 1);
    res.status(204).send();
});

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

				
			

Explanation:

  • app.use(bodyParser.json()): Middleware to parse JSON bodies.
  • app.get('/users', callback): Fetches all users.
  • app.post('/users', callback): Creates a new user.
  • app.get('/users/:id', callback): Fetches a user by ID.
  • app.put('/users/:id', callback): Updates a user by ID.
  • app.delete('/users/:id', callback): Deletes a user by ID

Output:

This script provides a full CRUD API for managing users. You can interact with this API using tools like Postman or CURL.

Express.js is a powerful and flexible framework for building web applications and APIs with Node.js. It provides a robust set of features and middleware, making it easy to develop complex applications quickly. This chapter has covered the basics to advanced usage of Express.js, from setting up a server, routing, and middleware, to handling forms and file uploads, using templating engines, error handling, and building RESTful APIs. With the examples and explanations provided, you should have a solid foundation to start developing your own Express.js applications.Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India