http module in Node.js
The http
module in Node.js is one of the core modules and is essential for creating web servers and making HTTP requests. It provides the functionality to handle HTTP requests and responses, enabling the creation of both HTTP servers and clients. Here's a detailed overview of the http
module, including how to create an HTTP server and client, and the main methods and properties it provides.
Creating an HTTP Server
Basic Example
Creating an HTTP server is straightforward. The server listens on a specified port and hostname, handling incoming requests and sending responses.
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
res.statusCode = 200; // Set the status code to 200 (OK)
res.setHeader('Content-Type', 'text/plain'); // Set the response header
res.end('Hello, World!\n'); // Send the response body
});
// Specify the port and hostname for the server to listen on
const hostname = '127.0.0.1';
const port = 3000;
// Start the server
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Handling Different HTTP Methods
You can handle different HTTP methods (GET, POST, etc.) by checking the req.method
property.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, GET request!');
} else if (req.method === 'POST' && req.url === '/') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(`Hello, POST request! Data: ${body}`);
});
} else {
res.statusCode = 404;
res.end('Not Found');
}
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
Creating an HTTP Client
Basic Example
Creating an HTTP client to make a GET request is also simple. You can use the http.get
method for making GET requests or http.request
for more control over the request.
const http = require('http');
const options = {
hostname: 'example.com',
port: 80,
path: '/',
method: 'GET'
};
// Make a GET request
const req = http.request(options, (res) => {
console.log(`Status Code: ${res.statusCode}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`Body: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`Problem with request: ${e.message}`);
});
// End the request
req.end();
Sending Data with POST Request
const http = require('http');
const data = JSON.stringify({
name: 'John Doe',
age: 30
});
const options = {
hostname: 'example.com',
port: 80,
path: '/submit',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
// Make a POST request
const req = http.request(options, (res) => {
console.log(`Status Code: ${res.statusCode}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`Body: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`Problem with request: ${e.message}`);
});
// Write data to request body
req.write(data);
// End the request
req.end();
Main Methods and Properties
Methods
- http.createServer([options][, requestListener]): Creates a new HTTP server.
- http.request(options[, callback]): Makes a request to a server.
options
is an object that specifies the request details. - http.get(options[, callback]): A shortcut for
http.request
with themethod
set toGET
.
Properties
- request: Represents the HTTP request and includes properties like
method
,url
,headers
, etc. - response: Represents the HTTP response and includes methods like
writeHead(statusCode[, statusMessage][, headers])
,write(chunk[, encoding][, callback])
,end([data][, encoding][, callback])
.
Practical Applications
- Web Servers: Build web servers that handle HTTP requests and responses.
- API Clients: Create clients to interact with external APIs.
- Proxies: Develop proxy servers to forward requests to other servers.
- Microservices: Communicate between different microservices in a microservice architecture.