Handling HTTP Requests and Responses

Tutorial 2 of 5

1. Introduction

This tutorial aims to provide a comprehensive guide on handling HTTP requests and responses using Node.js. By the end of this tutorial, you should be able to interpret client requests, generate suitable server responses, and understand the basics of working with HTTP in Node.js.

What you will learn:
- The foundations of HTTP requests and responses.
- How to work with HTTP in Node.js.
- How to handle different types of HTTP requests.
- How to generate and send HTTP responses.

Prerequisites:
- Basic understanding of JavaScript.
- Familiarity with Node.js.

2. Step-by-Step Guide

HTTP stands for HyperText Transfer Protocol. It is the foundation of data communication on the world wide web. Different HTTP methods correspond to CRUD operations: POST (Create), GET (Read), PUT (Update), and DELETE (Delete).

In Node.js, we can use the inbuilt HTTP module to make requests, and we use the http.createServer() method to create a server instance. The server listens to client requests and sends back responses.

HTTP Requests

An HTTP request is a message sent by the client to the server. It consists of the following:
- Request Line: Includes the HTTP method, URL, and HTTP version.
- Headers: Additional information like content type, authentication, etc.
- Body: Contains data to be sent to the server (optional).

HTTP Responses

An HTTP response is what is sent by the server to the client in response to an HTTP request. It contains:
- Status Line: Includes the HTTP version, status code, and status message.
- Headers: Additional information like content type, content length, server information, etc.
- Body: Contains data sent back from the server (optional).

3. Code Examples

Here's a simple example of a server that listens for any request and sends back a "Hello, World!" message.

const http = require('http'); // Import HTTP module

// Create server
const server = http.createServer((req, res) => {
  res.statusCode = 200; // Set status code to 200 (OK)
  res.setHeader('Content-Type', 'text/plain'); // Set content type to plain text
  res.end('Hello, World!\n'); // End response with a message
});

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

In this code, we create a server that listens on port 3000. Whenever a request is received, it sets the status code to 200 and the content type to text/plain, then ends the response with the message 'Hello, World!\n'.

4. Summary

We've covered the basics of handling HTTP requests and responses in Node.js. You have learned about HTTP methods, how to create a server in Node.js, and how to send responses back to the client.

Next Steps:
- Learn about RESTful APIs and how they use HTTP methods for CRUD operations.
- Explore frameworks like Express.js which simplify handling HTTP requests and responses.

Additional Resources:
- Node.js HTTP documentation
- MDN HTTP guide

5. Practice Exercises

Exercise 1: Create a server that listens on port 5000 and responds with "Welcome to Node.js!".

Solution:

const http = require('http'); // Import HTTP module

// Create server
const server = http.createServer((req, res) => {
  res.statusCode = 200; // Set status code to 200 (OK)
  res.setHeader('Content-Type', 'text/plain'); // Set content type to plain text
  res.end('Welcome to Node.js!\n'); // End response with a message
});

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

Exercise 2: Modify the server to send back a different message for different routes (e.g., '/' should return 'Home', '/about' should return 'About').

Solution:

const http = require('http'); // Import HTTP module

// Create server
const server = http.createServer((req, res) => {
  res.statusCode = 200; // Set status code to 200 (OK)
  res.setHeader('Content-Type', 'text/plain'); // Set content type to plain text

  // Check the request URL and respond accordingly
  if (req.url === '/') {
    res.end('Home\n');
  } else if (req.url === '/about') {
    res.end('About\n');
  } else {
    res.end('Not Found\n');
  }
});

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

This server responds with a different message depending on the requested route. If the route is not recognized, it returns 'Not Found'.