bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Node.js/Core Modules
Node.js•Core Modules

Node.js HTTP Module

The Built-in HTTP Module

Formula

Node.js includes a powerful built - in HTTP module that enables you to create HTTP servers and make HTTP requests.

This module is essential for building web applications and APIs in Node.js.

Key Features

Create HTTP servers to handle requests and send responses

Make HTTP requests to other servers

Handle different HTTP methods (GET, POST, PUT, DELETE, etc.)

Work with request and response headers

Handle streaming data for large payloads

Including the HTTP Module

To use the HTTP module, include it in your application using the require() method: // Using CommonJS require (Node.js default)

const http = require('http');

Formula

// Or using ES modules (Node.js 14 + with "type": "module" in package.json)
// import http from 'http';

Creating an HTTP Server

The HTTP module's createServer()

method creates an HTTP server that listens for requests on a specified port and executes a callback function for each request.

Basic HTTP Server Example

// Import the HTTP module const http = require('http');
// Create a server object const server = http.createServer((req, res) => {

Formula

// Set the response HTTP header with HTTP status and Content type res.writeHead(200, { 'Content - Type': 'text/plain' });

// Send the response body as 'Hello, World!'

res.end('Hello, World!\n');
});
// Define the port to listen on const PORT = 3000;
// Start the server and listen on the specified port server.listen(PORT, 'localhost', () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Understanding the Code http.createServer()
  • Creates a new HTTP server instance The callback function is executed for each request with two parameters: req - The request object (http.IncomingMessage) res - The response object (http.ServerResponse) res.writeHead() - Sets the response status code and headers res.end() - Sends the response and ends the connection server.listen() - Starts the server on the specified port

Running the Server

Save the code in a file named server.js Run the server using Node.js: node server.js Visit http://localhost:3000 in your browser to see the response.

Working with HTTP Headers

HTTP headers let you send additional information with your response.
The res.writeHead()

method is used to set the status code and response headers.

Setting Response Headers

Example: Setting Multiple Headers const http = require('http');

const server = http.createServer((req, res) => {
// Set status code and multiple headers res.writeHead(200, {

Formula

'Content - Type': 'text/html',
'X - Powered - By': 'Node.js',
'Cache - Control': 'no - cache, no - store, must - revalidate',
'Set-Cookie': 'sessionid=abc123; HttpOnly'
});
res.end('<h1>Hello, World!</h1>');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});

Common HTTP Status Codes

Code

Message

Description

200 OK

Standard response for successful HTTP requests

201

Created

Request has been fulfilled and new resource created 301

Moved Permanently

Resource has been moved to a new URL 400

Bad Request

Server cannot process the request due to client error 401

Unauthorized

Authentication is required

403

Forbidden

Server refuses to authorize the request

404

Next

Node.js HTTPS Module