http Module #
In Node.js, the http module is a core module that provides functionality for creating HTTP servers and clients. It is a foundational part of building web applications and APIs. Below is a basic overview of using the http module for server creation in Node.js:
Creating an HTTP Server: #
Use the createServer method to create a basic HTTP server:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Handling Requests and Responses: #
The server callback function is executed for every incoming HTTP request. It receives the request (req) and response (res) objects:
const server = http.createServer((req, res) => {
// Handle the request
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
HTTP Methods and Routing: #
Use the req.method property to determine the HTTP method, enabling basic routing:
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
} else if (req.method === 'GET' && req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About Us');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
Handling Query Parameters: #
Use the url module to parse query parameters:
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const name = parsedUrl.query.name || 'Node.js';
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Hello, ${name}!`);
});
Handling POST Requests: #
For POST requests, use the data event to collect the request body:
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/submit') {
let data = '';
req.on('data', chunk => {
data += chunk;
});
req.on('end', () => {
const parsedData = JSON.parse(data);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(parsedData));
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
Handling Static Files: #
Serve static files by reading and streaming the file content:
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, 'public', req.url);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
});
});
Handling Redirects: #
Redirect requests using the res.writeHead with a 302 status code:
const server = http.createServer((req, res) => {
if (req.url === '/old') {
res.writeHead(302, { 'Location': '/new' });
res.end();
} else if (req.url === '/new') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the new page!');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
Handling Cookies: #
Parse and set cookies using the req.headers.cookie and res.setHeader:
const server = http.createServer((req, res) => {
const cookies = req.headers.cookie || '';
// Set a cookie
res.setHeader('Set-Cookie', 'username=John; Path=/');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Cookies: ${cookies}`);
});
HTTP Server Events: #
Listen for server events such as ‘request’, ‘connection’, and ‘close’:
const server = http.createServer();
server.on('request', (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
server.on('connection', (socket) => {
console.log('Client connected');
});
server.on('close', () => {
console.log('Server closed');
});
server.listen(3000);
HTTPS Server: #
Create an HTTPS server using the https module:
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('public-cert.pem')
};
const server = https.createServer(options, (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
server.listen(3000);
The http module in Node.js is fundamental for creating web servers, handling requests, and building the backbone of web applications. It provides a versatile set of functionalities, allowing developers to handle different aspects of HTTP communication efficiently. While many modern applications use higher-level frameworks, understanding the basics of the http module is crucial for gaining insights into how web servers operate in a Node.js environment.