DEV Community

Cover image for Express.js - Essential Things to Know
Ryoichi Homma
Ryoichi Homma

Posted on • Edited on

Express.js - Essential Things to Know

This article focuses on essential things to know Express.js, a key part of building backend applications with Node.js. I'll dive into routing, CRUD operations, response methods, and middleware functions, all of which play a critical role in building robust web applications.

Concept Highlights:

  1. Route Methods and CRUD
  2. Routing Parameters
  3. Route Handlers
  4. Response Methods
  5. Built-in Middleware Functions

1. Route Methods and CRUD

In Express.js, route methods define how your application responds to different HTTP requests (e.g., GET, POST, PUT, DELETE) for specific routes. These methods are used to implement CRUD (Create, Read, Update, Delete) operations in your application.

Basic CRUD example: In this example, each route responds to a different CRUD operation based on the HTTP method used.

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

// Create - POST
app.post('/users', (req, res) => {
  res.send('User created');
}); 

// Read - GET
app.get('/users', (req, res) => {
  res.send('Here is the user'); 
}); 

// Update - PUT
app.put('/users/:id', (req, res) => {
  res.send('User with ID ${req.params.id} updated'); 
});

// Delete - DELETE
app.delete('/users//:id', (req, res) => {
  res.send('User with ID ${req.params.id} deleted');
}):

app.listen(3000, () => 
  console.log('Server running on port 3000')
);
Enter fullscreen mode Exit fullscreen mode

2. Routing Parameters

Routing parameters allow you to capture specific parts of the request URL and use them within your route handlers. For instance, you can extract an ID from the URL and use it to perform an action related to that ID.

e.g.) In this example, :id is a dynamic parameter, which will be extracted and used in the response. If this dynamic parameter is 123, a request to /users/123 will return "Fetching user with ID: 123."

app.get('/users/:id', (req, res) => {
  const userId = req.params.id; 
  res.send(`Fetching user with ID: ${userId}`);
});
Enter fullscreen mode Exit fullscreen mode

3. Route Handlers

Route handlers define how your server handles HTTP requests. You can define multiple middleware functions within a single route, allowing for cleaner and modular code.

Example with multiple handlers: In this example, the first middleware logs a message, and the second middleware sends the response.

app.get('/users', (req, res, next) => {
  console.log('First middleware');
  next(); // call the next handler in the stack
}, (req, res) => {
  res.send('User list'); 
});
Enter fullscreen mode Exit fullscreen mode

4. Response Methods

Express.js provides several methods for sending responses to the client. Let's explore some commonly used response methods.

a) .json() sends a JSON response.

app.get('/data', (req, res) => {
  res.json({ message: 'Hello, JSON' });
});
Enter fullscreen mode Exit fullscreen mode

b) .send() sends a response of various types (text, HTML, buffer, etc.).

app.get('/text', (req, res) => {
  res.send('Sending text');
});
Enter fullscreen mode Exit fullscreen mode

c) .download() sends a file as an attachment, prompting the user to download it.

app.get('/download', (req, res) => {
  res.download('path/to/file.pdf');
});
Enter fullscreen mode Exit fullscreen mode

d) .redirect() redirects the client to a different URL.

app.get('/redirect', (req, res) => {
  res.redirect('https://example.com');
});
Enter fullscreen mode Exit fullscreen mode

5. Built-in Middleware Functions

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function. They are used for modifying the request or response objects, ending the request-response cycle, or calling the next middleware.

a) express.static: this middleware serves static files (like images, CSS files, etc.) from a directory.

e.g.) In this example, any file in the public directory can be accessed via the browser like localhost:3000/image.jpg.

app.use(express.static('public'));
Enter fullscreen mode Exit fullscreen mode

b) express.json: this middleware parses incoming JSON payloads from the client.

e.g.) This is essential when handling POST or PUT requests with JSON data.

app.use(express.json());
Enter fullscreen mode Exit fullscreen mode

c) express.urlencoded: this middleware parses URL-encoded payloads (typically from form submissions).

e.g.) The extended: true option allows for parsing nested objects.

app.use(express.urlencoded({ extended: true }));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)