Comprehensive Guide and API Reference for Using HTTP Server in Node.js
An http-server
is a critical component in web development. It responds to incoming client requests on specific ports and routes them to appropriate handlers. In this guide, we will explore various API functionalities of the HTTP module in Node.js, along with some practical code snippets.
Getting Started
Before diving into the APIs, ensure you have Node.js installed on your machine. To begin using http
in your Node.js application, require the module:
const http = require('http');
Creating a Simple HTTP Server
Here’s how to create a basic HTTP server that will respond with “Hello, World!” to any request:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(3000, () => {
console.log('Server running at http://127.0.0.1:3000/');
});
Handling Different Routes
You can handle different routes based on the request URL:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
if (req.url === '/') {
res.end('Welcome to the homepage!\n');
} else if (req.url === '/about') {
res.end('Learn more about us here.\n');
} else {
res.statusCode = 404;
res.end('Page not found\n');
}
});
server.listen(3000, () => {
console.log('Server running at http://127.0.0.1:3000/');
});
Using JSON Responses
Many modern applications use JSON for communication. Here’s how to respond with JSON:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
const response = {
message: 'This is a JSON response',
timestamp: new Date()
};
res.end(JSON.stringify(response));
});
server.listen(3000, () => {
console.log('Server running at http://127.0.0.1:3000/');
});
Handling POST Requests
Handling POST requests involves capturing data from the request body. Here’s an example:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
res.end('Received data: ' + body);
});
} else {
res.statusCode = 405; // Method Not Allowed
res.end('POST method required');
}
});
server.listen(3000, () => {
console.log('Server running at http://127.0.0.1:3000/');
});
Implementing Middleware
You can implement simple middleware functions to preprocess requests:
const http = require('http');
const requestLogger = (req, res, next) => {
console.log(`${new Date()} - ${req.method} ${req.url}`);
next();
};
const server = http.createServer((req, res) => {
requestLogger(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Request logged!\n');
});
});
server.listen(3000, () => {
console.log('Server running at http://127.0.0.1:3000/');
});
Example Application
Here’s an example application that combines these concepts:
const http = require('http');
const requestHandler = (req, res) => {
res.setHeader('Content-Type', 'application/json');
if (req.method === 'GET' && req.url === '/') {
res.end(JSON.stringify({ message: 'Welcome to the homepage!' }));
} else if (req.method === 'GET' && req.url === '/about') {
res.end(JSON.stringify({ message: 'About us page' }));
} else if (req.method === 'POST' && req.url === '/data') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
res.end(JSON.stringify({ received: body }));
});
} else {
res.statusCode = 404;
res.end(JSON.stringify({ error: 'Not Found' }));
}
};
const server = http.createServer(requestHandler);
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});
By leveraging these APIs, you can create robust and flexible servers to handle client requests efficiently.
Hash: 71604076cde89575ddb846bef3255f506d4a532cdd4621ad03aae8f9a51eccf2