Handling Requests and Responses

Tutorial 3 of 5

Handling Requests and Responses in Express.js

1. Introduction

This tutorial will guide you through the process of handling HTTP requests and responses using Express.js, a popular Node.js web application framework. You will learn how to extract information from requests, how to construct and send responses back to the client, and best practices for managing these tasks.

By the end of this tutorial, you'll be able to:

  • Retrieve data from GET and POST requests
  • Send responses with various HTTP status codes
  • Handle errors in your Express.js application

Prerequisites: Basic understanding of JavaScript and familiarity with Node.js and Express.js. If you're new to these, you might want to check out some introductory tutorials first.

2. Step-by-Step Guide

Express.js provides a simple API for handling requests and responses. The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. The res object represents the HTTP response that an Express app sends when it gets an HTTP request.

Example: Handling GET Requests

// This is a route handler for GET requests to the / route
app.get('/', (req, res) => {
  // Send a response back to the client
  res.send('Hello, World!');
});

Example: Handling POST Requests

// This is a route handler for POST requests to the / route
app.post('/', (req, res) => {
  // Send a response back to the client
  res.send('You made a POST request');
});

3. Code Examples

Example 1: Extract Query Parameters from GET Requests

app.get('/search', (req, res) => {
  // req.query contains the query parameters
  console.log(req.query);
  res.send(`You searched for ${req.query.q}`);
});

When you visit http://localhost:3000/search?q=express, the app responds with "You searched for express", and console.log(req.query) outputs { q: 'express' }.

Example 2: Extract Data from POST Requests

// In order to parse incoming requests with JSON payloads, we use express.json() middleware
app.use(express.json());

app.post('/login', (req, res) => {
  // req.body contains the body of the request
  console.log(req.body);
  res.send(`Welcome, ${req.body.username}`);
});

If you make a POST request to http://localhost:3000/login with { "username": "John" } as the body, the app responds with "Welcome, John", and console.log(req.body) outputs { username: 'John' }.

4. Summary

In this tutorial, we've covered how to handle GET and POST requests in Express.js, how to extract data from these requests, and how to send responses back to the client. As a next step, you could explore handling PUT and DELETE requests, or look at using middleware for tasks such as error handling and logging.

5. Practice Exercises

  1. Create an Express app that responds with "Hello, [name]" when a GET request is made to the "/greet" route with a name query parameter.
  2. Create an Express app that accepts POST requests at the "/data" route, logs the request body to the console, and responds with a status code of 200.
  3. Create an Express app that responds with a custom error message and a status code of 404 when a GET request is made to an undefined route.

Solutions:

app.get('/greet', (req, res) => {
  res.send(`Hello, ${req.query.name}`);
});
app.post('/data', (req, res) => {
  console.log(req.body);
  res.sendStatus(200);
});
app.use((req, res) => {
  res.status(404).send('Sorry, we could not find that!');
});