Express.js / Handling Requests and Responses

Working with Request and Response Objects

In this tutorial, you will learn how to work with request and response objects in Express. This includes understanding their properties and methods, and how to use them to handle …

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores working with request and response objects in Express.

1. Introduction

In this tutorial, we will delve into the world of web development using Express.js, a popular framework for Node.js, by learning about Request and Response objects.

Objective

  • Understand the concepts of Request and Response objects in Express.js
  • Learn how to utilize their properties and methods in handling HTTP requests and responses

Learning Outcomes

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

  • Explain the role of Request and Response objects in Express.js
  • Use the properties and methods of Request and Response objects
  • Handle HTTP requests and responses effectively

Prerequisites

  • Basic knowledge of JavaScript
  • Familiarity with Node.js and Express.js

2. Step-by-Step Guide

In Express.js, req (request) and res (response) are objects that encapsulate client request and server response, respectively. They contain a wealth of information and methods needed in web development.

Request Object

The request object (req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.

Example:

app.get('/user/:id', function(req, res) {
    console.log(req.params);
    res.send('User Info');
});

In the example above, req.params is used to retrieve the route parameters. When you navigate to /user/42 in your browser, it will log { id: '42' }.

Response Object

The response object (res) represents the HTTP response that an Express.js app sends when it gets an HTTP request. It has methods for sending HTTP responses such as res.send(), res.json(), res.render(), etc.

Example:

app.get('/', function(req, res) {
    res.send('Hello World');
});

In the example above, res.send() is used to send a response back to the client.

3. Code Examples

Example 1: Using req.query

// Assuming you're running on localhost:3000
app.get('/search', function(req, res) {
    console.log(req.query);
    res.send('Search Results');
});

When you navigate to localhost:3000/search?keyword=express, the console will log { keyword: 'express' }.

Example 2: Using res.json()

app.get('/api/data', function(req, res) {
    const data = { name: 'John', age: 25 };
    res.json(data);
});

In the example above, res.json() is used to send a JSON response. Navigating to localhost:3000/api/data will show { "name": "John", "age": 25 } in the browser.

4. Summary

In this tutorial, we have learned about the Request and Response objects in Express.js and their common properties and methods. You're now able to handle HTTP requests and responses effectively.

Next Steps

Try to explore more properties and methods of req and res in the Express.js documentation.

Additional Resources

5. Practice Exercises

  1. Exercise 1: Create an Express.js application that responds with the user's IP address and browser information when visited at /info.

  2. Exercise 2: Create an Express.js application that accepts POST requests at /login and responds with a success message if the username and password are correct.

  3. Exercise 3: Create an Express.js application that serves JSON data of all the users when visited at /api/users.

Note: For these exercises, you might need to install additional middleware like body-parser to parse incoming request bodies. Also, to test POST requests, you can use tools like Postman.

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

Favicon Generator

Create favicons from images.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

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