Working with Express.js in Node.js

Express.js is one of the most popular web application frameworks for Node.js. It simplifies the process of building web applications and APIs by providing a robust set of features for handling routing, middleware, and HTTP requests. In this module, we will explore how to set up and use Express.js to build a basic web server and API.


Table of Contents

  1. Introduction to Express.js
  2. Installing and Setting Up Express.js
  3. Building a Basic Web Server with Express
  4. Handling Routes and HTTP Methods
  5. Working with Middleware in Express
  6. Building RESTful APIs with Express
  7. Error Handling in Express.js
  8. Conclusion

1. Introduction to Express.js

Express.js is a minimal and flexible Node.js web application framework that provides a set of tools to build web applications and APIs. It abstracts much of the complexity involved in managing HTTP requests and responses, making it easier for developers to build and maintain applications.

Express simplifies routing, which is the process of handling incoming requests, and it allows developers to create endpoints to respond to different HTTP methods such as GET, POST, PUT, and DELETE. Express also allows for easy integration with middleware, which can be used for various tasks such as authentication, logging, error handling, and more.

With its easy-to-use API, Express has become one of the most widely used frameworks for Node.js development.


2. Installing and Setting Up Express.js

Before we begin using Express, we need to install it. Express is available via npm, so we can install it easily by running the following command in your project directory:

npm install express --save

Step 1: Creating the Basic Express App

Once Express is installed, you can create a simple Express server with just a few lines of code. In your project directory, create a new file named app.js (or any name you prefer).

Here is how you set up a simple Express server:

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

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

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

Step 2: Running the Server

To run your Express server, use the following command:

node app.js

After running this command, you can visit http://localhost:3000 in your browser, and you should see the message “Hello, Express!” displayed.


3. Building a Basic Web Server with Express

Now that we have a basic server up and running, let’s explore how to handle different HTTP methods and routes.

Handling GET Requests

The app.get() method is used to handle GET requests to a specific URL or route. You can define routes with dynamic segments, which allows for capturing parameters from the URL.

app.get('/greet/:name', (req, res) => {
const name = req.params.name;
res.send(`Hello, ${name}!`);
});

This will return a personalized greeting when you visit http://localhost:3000/greet/John.

Handling POST Requests

The app.post() method is used to handle POST requests. It’s commonly used for handling form submissions or sending data to the server.

app.post('/submit', (req, res) => {
res.send('Form submitted successfully!');
});

4. Handling Routes and HTTP Methods

Express allows you to handle all standard HTTP methods (GET, POST, PUT, DELETE) through route handlers. Here’s how you can manage these methods in your application:

// Handle GET request
app.get('/data', (req, res) => {
res.json({ message: 'GET request received' });
});

// Handle POST request
app.post('/data', (req, res) => {
res.json({ message: 'POST request received' });
});

// Handle PUT request
app.put('/data', (req, res) => {
res.json({ message: 'PUT request received' });
});

// Handle DELETE request
app.delete('/data', (req, res) => {
res.json({ message: 'DELETE request received' });
});

5. Working with Middleware in Express

Middleware functions are essential in Express, allowing you to add functionality to your application, such as authentication, logging, and error handling. Middleware can be applied globally or to specific routes.

Example: Basic Logging Middleware

This middleware will log the details of each incoming request.

app.use((req, res, next) => {
console.log(`Request Method: ${req.method}, Request URL: ${req.url}`);
next(); // Move to the next middleware or route handler
});

Example: Error Handling Middleware

You can define custom error handling middleware to handle errors that occur during request processing.

app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});

6. Building RESTful APIs with Express

One of the most common use cases for Express is to build RESTful APIs. RESTful APIs use HTTP methods to perform CRUD (Create, Read, Update, Delete) operations.

Here’s an example of building a simple API for managing users:

Example: Simple User API

let users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' },
];

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

// Get a single 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);
});

// Add a new user
app.post('/users', (req, res) => {
const newUser = { id: users.length + 1, name: req.body.name };
users.push(newUser);
res.status(201).json(newUser);
});

// Update an existing user
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');
user.name = req.body.name;
res.json(user);
});

// Delete a user
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();
});

7. Error Handling in Express.js

Handling errors is an important part of building reliable applications. In Express, you can define custom error handling middleware. For example, handling 404 errors when a route is not found:

app.use((req, res, next) => {
res.status(404).send('Route not found');
});

Express also allows you to handle other types of errors globally with a custom error handler that will capture any uncaught errors:

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

8. Conclusion

In this module, we explored how to set up Express.js to build web servers and APIs. We covered the basics of handling HTTP requests, working with middleware, and building a simple RESTful API. Express is a powerful tool that helps simplify the process of building applications with Node.js, and it’s essential for any full-stack JavaScript developer.