Node.js is a powerful JavaScript runtime that enables server-side development. One of its core modules is the http module, which allows developers to create web servers and handle HTTP requests and responses directly without relying on external libraries like Express.js. This gives you full control and transparency over how the server behaves and responds to different HTTP request methods such as GET, POST, PUT, DELETE, and others.
In this document, we will cover how to use the http module to build a basic server and then handle different types of requests, including parsing incoming data, sending appropriate responses, handling routes, managing headers, and maintaining proper HTTP status codes.
The http module is built into Node.js. You donβt need to install it separately.
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
HTTP defines several methods for client-server communication. The most common ones include:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Home Page');
} else if (req.method === 'POST' && req.url === '/submit') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Data Submitted');
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
GET is the most basic and commonly used HTTP method. It's used to request data from the server.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/info') {
res.writeHead(200, {'Content-Type': 'application/json'});
const data = { message: 'This is a GET response' };
res.end(JSON.stringify(data));
}
});
server.listen(3000);
POST requests are used to send data to the server. This is often done when submitting forms or uploading files.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/submit') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
console.log('Received Data:', body);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Data received');
});
}
});
server.listen(3000);
PUT requests are used to update or replace resources. Similar to POST, PUT usually includes a request body.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'PUT' && req.url === '/update') {
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
console.log('Updated Data:', body);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Resource updated');
});
}
});
server.listen(3000);
DELETE requests are used to delete a resource on the server.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'DELETE' && req.url === '/delete') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Resource deleted');
}
});
server.listen(3000);
You can use the built-in URL module to parse query strings from a GET request.
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
if (req.method === 'GET' && parsedUrl.pathname === '/search') {
const query = parsedUrl.query;
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query));
}
});
server.listen(3000);
HTTP headers give clients and servers information about the request and response. Examples include content type, length, cache settings, etc.
res.writeHead(200, {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
});
Status codes are crucial for client-server communication.
if (!data) {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end('Missing Data');
}
const fs = require('fs');
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
fs.readFile('index.html', (err, data) => {
if (err) {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Server error');
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
}
});
}
});
server.listen(3000);
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/json') {
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
const parsed = JSON.parse(body);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({ received: parsed }));
});
}
});
server.listen(3000);
function handleGet(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('GET route');
}
function handlePost(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('POST route');
}
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET') return handleGet(req, res);
if (req.method === 'POST') return handlePost(req, res);
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Route not found');
});
server.listen(3000);
const http = require('http');
const server = http.createServer((req, res) => {
console.log(`${req.method} ${req.url}`);
res.writeHead(200);
res.end('Logged');
});
server.listen(3000);
The HTTP module in Node.js gives you a low-level and powerful interface to handle different types of HTTP requests without relying on external frameworks. This allows for complete control over routing, request parsing, response formatting, and status code handling. While modern applications often use higher-level frameworks like Express, understanding how the core http module works is essential for building lightweight, efficient, and flexible services.
By mastering the handling of GET, POST, PUT, DELETE, and other HTTP methods, parsing query strings and body content, and returning meaningful responses with the correct headers and status codes, you can build powerful and scalable HTTP servers using nothing but Node.js and the built-in http module.
A function passed as an argument and executed later.
Runs multiple instances to utilize multi-core systems.
Reusable blocks of code, exported and imported using require() or import.
nextTick() executes before setImmediate() in the event loop.
Starts a server and listens on specified port.
Node Package Manager β installs, manages, and shares JavaScript packages.
A minimal and flexible web application framework for Node.js.
A stream handles reading or writing data continuously.
It processes asynchronous callbacks and non-blocking I/O operations efficiently.
Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.
An object representing the eventual completion or failure of an asynchronous operation.
require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).
Use module.exports or exports.functionName.
Variables stored outside the code for configuration, accessed using process.env.
MongoDB, often used with Mongoose for schema management.
Describes project details and manages dependencies and scripts.
Synchronous blocks execution; asynchronous runs in background without blocking.
Allows or restricts resources shared between different origins.
Use try-catch, error events, or middleware for error handling.
Provides file system-related operations like read, write, delete.
Using event-driven architecture and non-blocking I/O.
Functions in Express that execute during request-response cycle.
A set of routes or endpoints to interact with server logic or databases.
Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.
Middleware to parse incoming request bodies, like JSON or form data.
Copyrights © 2024 letsupdateskills All rights reserved