Understanding Node.js HTTP Core Module and Building a Simple Server and Client
This article introduces Node.js’s built‑in HTTP core module, explains its main classes and functions, and demonstrates how to create a simple HTTP server and a client in JavaScript, illustrating request handling, response generation, and data exchange between the two.
With the powerful support of various frameworks, Node.js development has become increasingly convenient, but stepping away from those frameworks prompts a clear and deep understanding of Node.js core modules and low‑level APIs; this series revisits the core modules of Node.js.
The HTTP protocol is the most widely used application‑layer communication protocol, and Node's built‑in http module allows us to quickly build HTTP servers and clients for data exchange.
HTTP Module API Overview
Class: http.Agent – Manages connection pooling and keeps sockets alive for long‑lived communications, avoiding the overhead of repeatedly opening and closing connections.
Class: http.ClientRequest – Created internally by http.request() , this event emitter represents a client request and provides methods to abort, finish, set timeouts, and send data chunks.
Class: http.Server – Represents the server object, listening for client requests, handling connections, and exposing methods to set timeouts, listen on ports, and close the server.
Class: http.ServerResponse – Generated by the server for each response, allowing status code handling, timeout configuration, and header manipulation.
Class: http.IncomingMessage – Produced by http.Server or http.ClientRequest , it is passed to request and response events and provides access to status, headers, and data.
http.METHODS – An array of supported HTTP method names.
http.STATUS_CODES – A collection of standard HTTP status codes and their descriptions.
http.createServer([requestListener]) – Creates an HTTP server and returns an http.Server instance.
http.get(options, [callback]) – A convenience method for simple GET requests, a special case of http.request() .
http.globalAgent – The default global Agent instance used by all HTTP client requests.
http.request(options, [callback]) – Initiates an HTTP request and returns an http.ClientRequest object.
HTTP Code Practice
Create HTTP Server
const http = require('http');
const hostname = '127.0.0.1';
const port = 3456;
const server = http.createServer((req, res) => {
console.log(`request url: ${req.url}`);
if (req.url === '/http') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('this is server response.');
} else {
res.statusCode = 404;
res.end('not found!');
}
req.on('data', (chunk) => {
console.log(`request data from client: ${chunk}`);
});
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
This code creates a server that listens on 127.0.0.1:3456 ; it returns a 200 response with a message when the request URL is /http , otherwise it responds with 404.
Create HTTP Client
const http = require('http');
let options = {
hostname: '127.0.0.1',
port: 3456,
path: '/http',
method: 'post',
};
let req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`response from server : ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
req.write('this is client request.');
req.end();
This client code sends a POST request to /http on the previously created server, writes a string payload, and logs the server’s status code, headers, and response data.
Note: The server and client scripts should be placed in separate .js files and can be run directly from the command line.
In summary, we briefly reviewed the top‑level API of Node.js’s HTTP module and built a simple server‑client communication example.
System Architect Go
Programming, architecture, application development, message queues, middleware, databases, containerization, big data, image processing, machine learning, AI, personal growth.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.