The HTTP module is one of the core modules provided by Node.js, enabling you to create web servers and clients. It allows you to handle HTTP requests and responses directly using JavaScript. This tutorial will cover how to use the HTTP module to build a simple web server and client.
Node.js provides an http module that can be used to create both HTTP servers and clients. The module is built on top of the event-driven, non-blocking I/O model that makes Node.js highly efficient for handling multiple connections simultaneously.
To create an HTTP server using the http module, you need to use the createServer method. This method takes a callback function that is executed every time a request is received. The callback function receives two arguments: request and response.
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// Set the response header to plain text
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send a response back to the client
res.end('Hello, World!\n');
});
// Listen on port 3000
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
const http = require('http');const server = http.createServer((req, res) => { ... });
req (request object) and res (response object).res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
server.listen(3000, () => { ... });
To handle different routes in your server, you can check the request URL and respond accordingly.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Home Page\n');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About Page\n');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found\n');
}
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
if (req.url === '/') { ... }
To handle POST requests, you need to read the request body since it can contain data sent by the client.
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(); // Convert Buffer to string
});
req.on('end', () => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Received: ${body}\n`);
});
} else {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Method Not Allowed\n');
}
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
if (req.method === 'POST' && req.url === '/submit') { ... }
/submit.req.on('data', chunk => { body += chunk.toString(); }); reads the incoming data chunks.req.on('end', () => { ... }); is called when all data has been received.Node.js also allows you to create HTTP clients using the http module. This can be useful for making requests to external APIs or other servers.
const http = require('http');
// Options object
const options = {
hostname: 'example.com',
port: 80,
path: '/',
method: 'GET'
};
// Create a request
const req = http.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
req.on('error', (error) => {
console.error(`Problem with request: ${error.message}`);
});
// End the request
req.end();
hostname: The domain name of the server.port: The port number on which the server is listening.path: The path to the resource you want to access.method: The HTTP method (GET, POST, etc.).const req = http.request(options, (res) => { ... });
res.on('data', (chunk) => { data += chunk; }); reads the response data chunks.res.on('end', () => { console.log(data); }); is called when all data has been received.req.on('error', (error) => { ... }); handles any errors that occur during the request.req.end();
The HTTP module in Node.js is a powerful tool for building web servers and clients. By understanding how to create and manage HTTP servers, as well as making HTTP requests, you can build robust and efficient applications. This tutorial has covered the basics of using the HTTP module, including creating servers, handling different routes, managing POST requests, and creating clients. With this knowledge, you can start building your own web applications in Node.js.