Express.js / Express.js Basics

Handling Requests and Responses

This tutorial focuses on handling requests and responses in Express.js. You will learn how to retrieve information from requests and how to send responses back to the client.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers the fundamental concepts of Express.js, including installation, setup, and creating a basic application.

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!');
});

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help