In this section, we will delve into how to handle HTTP requests and responses in Node.js. This is a fundamental skill for building web servers and APIs. We will cover the following topics:

  1. Understanding HTTP Requests and Responses
  2. Creating a Simple HTTP Server
  3. Handling Different HTTP Methods
  4. Parsing Request Data
  5. Sending Responses

  1. Understanding HTTP Requests and Responses

HTTP Requests

An HTTP request is a message sent by a client to a server to request data or perform an action. It consists of:

  • Request Line: Contains the HTTP method (GET, POST, etc.), the URL, and the HTTP version.
  • Headers: Provide metadata about the request (e.g., content type, user agent).
  • Body: Contains data sent to the server (used in methods like POST).

HTTP Responses

An HTTP response is a message sent by a server to a client in response to an HTTP request. It consists of:

  • Status Line: Contains the HTTP version, status code, and status message.
  • Headers: Provide metadata about the response (e.g., content type, content length).
  • Body: Contains the data sent back to the client.

  1. Creating a Simple HTTP Server

Let's start by creating a simple HTTP server that listens for requests and sends back a basic response.

const http = require('http');

// Create an HTTP server
const server = http.createServer((req, res) => {
  // Set the response header
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  // Send the response body
  res.end('Hello, World!\n');
});

// The server listens on port 3000
server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

Explanation

  • http.createServer: Creates an HTTP server that listens for requests.
  • req: Represents the incoming request.
  • res: Represents the outgoing response.
  • res.writeHead: Sets the response status code and headers.
  • res.end: Ends the response and sends the data.

  1. Handling Different HTTP Methods

Different HTTP methods (GET, POST, PUT, DELETE) are used for different types of operations. Let's handle GET and POST requests.

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Received a GET request\n');
  } else if (req.method === 'POST') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Received a POST request\n');
  } else {
    res.writeHead(405, { 'Content-Type': 'text/plain' });
    res.end('Method Not Allowed\n');
  }
});

server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

Explanation

  • req.method: Checks the HTTP method of the request.
  • 405: Status code for "Method Not Allowed".

  1. Parsing Request Data

To handle data sent in a POST request, we need to parse the request body.

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method === 'POST') {
    let body = '';

    // Collect data chunks
    req.on('data', chunk => {
      body += chunk.toString();
    });

    // End of data
    req.on('end', () => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(`Received data: ${body}\n`);
    });
  } else {
    res.writeHead(405, { 'Content-Type': 'text/plain' });
    res.end('Method Not Allowed\n');
  }
});

server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

Explanation

  • req.on('data'): Listens for data chunks.
  • req.on('end'): Fires when all data has been received.

  1. Sending Responses

We can send different types of responses, such as JSON, HTML, or plain text.

Sending JSON Response

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Hello, World!' }));
  } else {
    res.writeHead(405, { 'Content-Type': 'text/plain' });
    res.end('Method Not Allowed\n');
  }
});

server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

Explanation

  • JSON.stringify: Converts a JavaScript object to a JSON string.

Practical Exercise

Exercise

  1. Create an HTTP server that handles GET and POST requests.
  2. For GET requests, respond with a JSON object containing a greeting message.
  3. For POST requests, parse the request body and respond with the received data in JSON format.

Solution

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Hello, World!' }));
  } else if (req.method === 'POST') {
    let body = '';

    req.on('data', chunk => {
      body += chunk.toString();
    });

    req.on('end') => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ receivedData: body }));
    });
  } else {
    res.writeHead(405, { 'Content-Type': 'text/plain' });
    res.end('Method Not Allowed\n');
  }
});

server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

Common Mistakes

  • Not ending the response: Always ensure res.end() is called to complete the response.
  • Incorrect Content-Type: Ensure the Content-Type header matches the type of data being sent.

Conclusion

In this section, we learned how to handle HTTP requests and responses in Node.js. We covered creating a simple HTTP server, handling different HTTP methods, parsing request data, and sending various types of responses. These skills are essential for building web servers and APIs. In the next section, we will explore how to serve static files and implement routing in our Node.js applications.

Node.js Course

Module 1: Introduction to Node.js

Module 2: Core Concepts

Module 3: File System and I/O

Module 4: HTTP and Web Servers

Module 5: NPM and Package Management

Module 6: Express.js Framework

Module 7: Databases and ORMs

Module 8: Authentication and Authorization

Module 9: Testing and Debugging

Module 10: Advanced Topics

Module 11: Deployment and DevOps

Module 12: Real-World Projects

© Copyright 2024. All rights reserved