Lesson 35 of 50 – Request and Response in Express.js
70% Completed
70%

Request and Response in Express.js

Learn how to receive information from clients, read URL parameters, access form and JSON data, send responses, and use HTTP status codes in Express.js applications.

In this lesson: You will learn about req, res, request methods, route parameters, query parameters, request bodies, response methods, headers, status codes, and practical examples.

1. What Is a Request?

A request is a message sent by a client, such as a browser, mobile application, or API client, to a server.

A request may contain:

  • The requested URL.
  • The HTTP method, such as GET or POST.
  • Headers containing additional information.
  • Query parameters and route parameters.
  • A request body containing submitted data.
Example of a Client Request
GET /students/101 HTTP/1.1
Host: localhost:3000

This request asks the server to retrieve information associated with student ID 101.

2. What Is a Response?

A response is the message returned by the server after processing a client request.

A response may contain:

  • An HTTP status code.
  • Response headers.
  • HTML, plain text, JSON, or other data.
Example of a Server Response
HTTP/1.1 200 OK
Content-Type: text/plain

Student found successfully

The status code 200 indicates that the request was successful.

3. Understand req and res

In Express.js route handlers, req represents the request object and res represents the response object.

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

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

app.listen(3000, () => {
    console.log('Server running on port 3000');
});
  • req provides information about the incoming request.
  • res sends a response back to the client.
  • res.send() sends the response content.

4. Read the Request Method and URL

You can inspect the HTTP method and URL using req.method and req.url.

Example: Request Information
const express = require('express');
const app = express();

app.use((req, res, next) => {
    console.log('Method:', req.method);
    console.log('URL:', req.url);
    next();
});

app.get('/', (req, res) => {
    res.send('Home Page');
});

app.listen(3000, () => {
    console.log('Server started');
});

When you visit the home page, the terminal logs:

Method: GET
URL: /

5. Read Route Parameters

Route parameters capture values from the URL path. Express makes them available through req.params.

Example: Student ID
const express = require('express');
const app = express();

app.get('/students/:id', (req, res) => {
    const studentId = req.params.id;

    res.send('Student ID: ' + studentId);
});

app.listen(3000, () => {
    console.log('Server started');
});

Visit:

http://localhost:3000/students/101
Output: Student ID: 101

6. Read Query Parameters

Query parameters are values included in the URL after a question mark. They are commonly used for searches and filters.

Example URL:

http://localhost:3000/search?name=Amit&course=Node.js
Example: Search Student
const express = require('express');
const app = express();

app.get('/search', (req, res) => {
    const name = req.query.name;
    const course = req.query.course;

    res.json({
        studentName: name,
        studentCourse: course
    });
});

app.listen(3000, () => {
    console.log('Server started');
});

Expected response:

{
  "studentName": "Amit",
  "studentCourse": "Node.js"
}

7. Read the Request Body

The request body contains data submitted by a client. For example, a student registration form might send a student's name, email, and course.

Important: Express does not automatically parse every request body. Register the appropriate body-parsing middleware before the routes that need it.

Example: Receive JSON Data

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

app.use(express.json());

app.post('/students', (req, res) => {
    const student = req.body;

    res.json({
        message: 'Student received',
        data: student
    });
});

app.listen(3000, () => {
    console.log('Server started');
});

Send this JSON body in a POST request:

{
    "name": "Amit",
    "course": "Node.js"
}

Example response:

{
  "message": "Student received",
  "data": {
    "name": "Amit",
    "course": "Node.js"
  }
}

Use Postman or another HTTP client to send the POST request with the Content-Type: application/json header.

8. Read HTML Form Data

HTML forms can submit URL-encoded data. Use express.urlencoded() to parse this type of request body.

Example: Registration Form Handler
const express = require('express');
const app = express();

app.use(express.urlencoded({ extended: false }));

app.post('/register', (req, res) => {
    const name = req.body.name;
    const course = req.body.course;

    res.send(
        'Welcome ' + name + '. Your course is ' + course
    );
});

app.listen(3000, () => {
    console.log('Server started');
});

The form should submit fields named name and course using the POST method.

9. Send a Text Response

Use res.send() to send a text or HTML response.

app.get('/message', (req, res) => {
    res.send('Welcome to Soopro Pathshala');
});

Visiting /message displays:

Welcome to Soopro Pathshala

10. Send a JSON Response

Use res.json() to send JSON data. This is common when building REST APIs for websites and mobile applications.

Example: Student Information
app.get('/student', (req, res) => {
    res.json({
        id: 101,
        name: 'Rahul',
        course: 'Node.js'
    });
});

Response:

{
  "id": 101,
  "name": "Rahul",
  "course": "Node.js"
}

11. Set HTTP Status Codes

An HTTP status code indicates the result of processing a request. Express lets you set the status using res.status().

Status Code Meaning Common Use
200 OK Request succeeded.
201 Created A resource was created successfully.
400 Bad Request The request contains invalid data.
401 Unauthorized Authentication is required or invalid.
403 Forbidden The client is not permitted to access the resource.
404 Not Found The requested resource was not found.
500 Internal Server Error An unexpected server error occurred.
Example: Send a 201 Response
app.post('/students', (req, res) => {
    res.status(201).json({
        message: 'Student created successfully'
    });
});

The status code 201 is commonly used after a resource has been created successfully.

12. Send Custom Response Headers

Response headers provide metadata about the server response. You can set a header using res.set().

Example: Custom Header
app.get('/headers', (req, res) => {
    res.set('X-App-Name', 'Soopro Pathshala');

    res.send('Custom response header added');
});

The response includes a custom header named X-App-Name.

13. Redirect a Client

The res.redirect() method redirects a client to another URL.

Example: Redirect to About Page
app.get('/old-page', (req, res) => {
    res.redirect('/about');
});

app.get('/about', (req, res) => {
    res.send('About Page');
});

When the client visits /old-page, Express redirects it to /about.

14. Important Request and Response Properties

Property or Method Purpose
req.method Reads the HTTP method.
req.url Reads the request URL.
req.params Reads route parameters.
req.query Reads query parameters.
req.body Accesses parsed request-body data.
req.get() Reads a request header.
res.send() Sends text or HTML content.
res.json() Sends JSON data.
res.status() Sets the HTTP status code.
res.set() Sets response headers.
res.redirect() Redirects the client.

15. Practical Assignment

Assignment: Student Request and Response API

Create an Express application with the following requirements:

  1. Create a GET route / that sends a welcome message.
  2. Create a GET route /students/:id that reads a student ID.
  3. Create a GET route /search?name=Amit that reads a query parameter.
  4. Use express.json() to parse JSON request bodies.
  5. Create a POST route /students that receives student data.
  6. Return a JSON response using res.json().
  7. Use status code 201 for a successful creation response.
  8. Create a route that sends a custom response header.
  9. Create a route that redirects to the home page.
Lesson Summary: You learned how to read request methods, URLs, route parameters, query parameters, and request bodies. You also learned to send text and JSON responses, set status codes and headers, and redirect clients.

Test Your Knowledge – MCQ Quiz

Select the correct answer for each question.

1. Which property reads route parameters in Express.js?
2. Which method sends JSON data to a client?
3. Which HTTP status code commonly indicates successful resource creation?