Node.js HTTP Module

The Node.js HTTP module is a core module that allows you to create and manage web servers. It provides functionality to handle HTTP requests and responses, making it an essential tool for building backend web applications.

What is the HTTP Module?

The HTTP module in Node.js is a built-in module that provides functionality to:

  • Create an HTTP server.
  • Handle HTTP requests and responses.
  • Communicate over the web using the HTTP protocol.

It allows developers to set up basic web servers without the need for additional libraries or frameworks.

How to Use the HTTP Module

To use the HTTP module, you must first import it using the require() function:

const http = require('http');

The HTTP module includes methods to create servers, send requests, and receive responses. The most commonly used method is http.createServer().

Creating a Simple HTTP Server

Here’s a step-by-step guide to creating a basic HTTP server using Node.js:

Example: Basic HTTP Server

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

// Create the server
const server = http.createServer((req, res) => {
// Set the response header
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send the response
res.end('Hello, welcome to my Node.js HTTP server!');
});

// Listen on port 3000
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});

Explanation:

  1. http.createServer(): Creates a new HTTP server.
  2. Request (req) and Response (res): These parameters allow you to handle incoming requests and send responses.
  3. res.writeHead(): Sets the HTTP status code (e.g., 200 for success) and headers (e.g., Content-Type).
  4. res.end(): Ends the response and sends data to the client.
  5. server.listen(): Specifies the port on which the server listens for incoming requests.

Steps to Run the Code:

Save the file as server.js.

Run the file in your terminal:

node server.js

Open your browser and visit http://localhost:3000.

Output:

Hello, welcome to my Node.js HTTP server!

Handling Requests and Responses

The HTTP module lets you handle requests sent by clients and respond accordingly.

Example: Handling Different Routes

const http = require('http');

const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the Home Page');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('This is the About Page');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Page Not Found');
}
});

server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});

Explanation:

  1. req.url: This property contains the URL of the incoming request.
  2. Route Handling: The if conditions check the requested URL and send appropriate responses.

Sending HTML Responses

You can send HTML content as a response by setting the Content-Type to text/html.

Example:

const http = require('http');

const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<head><title>Node.js HTTP Module</title></head>
<body>
<h1>Welcome to My Node.js Server</h1>
<p>This is a simple HTML response.</p>
</body>
</html>
`);
});

server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});

Real-World Application

The HTTP module is often used to build APIs. Here’s an example of a simple API returning JSON data:

Example: API with JSON Response

const http = require('http');

const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
const data = {
message: 'Hello, this is JSON data!',
status: 'success',
};
res.end(JSON.stringify(data));
});

server.listen(3000, () => {
console.log('API server running at http://localhost:3000');
});

Output:

When you visit http://localhost:3000, you’ll see:

{
"message": "Hello, this is JSON data!",
"status": "success"
}

Common Methods in the HTTP Module

  1. http.createServer(): Creates a new HTTP server.
  2. res.writeHead(): Sets the response status code and headers.
  3. res.end(): Ends the response.
  4. req.url: Provides the requested URL.
  5. req.method: Specifies the HTTP method (e.g., GET, POST).

Common Mistakes to Avoid

  1. Not Ending the Response: Always call res.end() to properly send the response to the client.
  2. Ignoring Content-Type: Set the correct Content-Type for the data you’re sending (e.g., text/plain, text/html or application/json).
  3. Not Handling Errors: Handle errors gracefully to avoid server crashes.

Leave a Comment

BoxofLearn