Building a Web Server with Node.js HTTP Module
The HTTP module is a core Node.js module for creating web servers. It allows you to transform a standard computer into a web server capable of serving resources, eliminating the need for external software like Apache or IIS.
To begin using the HTTP module, import it into your project:
const http = require('http');
Core Networking Concepts for Servers
An IP address is a unique numerical identifier for each device on a network, similar to a phone number. It's typically represented in dot-decimal notation (e.g., 192.168.1.1). During development, you can use the loopback address 127.0.0.1 to access your local machine as both server and client.
Domain names provide human-readable aliases for IP addresses (e.g., example.com). Domain Name System (DNS) servers handle the translation between domain names and IP addresses. For local developmant, localhost is the domain name equivalent of 127.0.0.1.
Creating a Basic Web Server
Follow these steps to create a functional web server:
- Import the HTTP module.
- Instantiate a server object.
- Bind a listener to the
requestevent to handle incoming client requests. - Start the server on a specific port.
// Step 1: Import module
const http = require('http');
// Step 2: Create server instance
const webServer = http.createServer();
// Step 3: Bind request event handler
webServer.on('request', (clientReq, serverRes) => {
console.log('New connection received.');
});
// Step 4: Start server on port 3000
webServer.listen(3000, () => {
console.log('Server active at http://127.0.0.1:3000');
});
The Request and Response Objects
The callback function for the request event receives two key objects:
req: Contains data about the client's request (URL, method, headers).res: Used to send data back to the client.
webServer.on('request', (req, res) => {
const requestPath = req.url;
const requestType = req.method;
const message = `Received a ${requestType} request for ${requestPath}`;
console.log(message);
// Send response to client
res.end(message);
});
Handling Character Encoding for Responses
When sending text containing non-ASCII characters (like Chinese), you must explicitly set the character encoding in the response headers to prevent garbled output.
webServer.on('request', (req, res) => {
const chineseText = `请求的路径是:${req.url},方法为:${req.method}`;
// Set header to specify UTF-8 encoding
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end(chineseText);
});
Practical Example: Routing Requests
A common server task is to return different content based on the requested URL. The following example demonstrates basic routing logic.
const http = require('http');
const server = http.createServer();
server.on('request', (req, res) => {
const path = req.url;
let pageContent = '<h1>Page Not Found</h1>';
if (path === '/' || path === '/home.html') {
pageContent = '<h1>Welcome to the Homepage</h1>';
} else if (path === '/info.html') {
pageContent = '<h1>Information Page</h1>';
}
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(pageContent);
});
server.listen(8080, () => {
console.log('Server ready on port 8080');
});