Node.js Web Module
Node.js - Building a Simple Web Server
Section titled “Node.js - Building a Simple Web Server”What is a Web Server?
Section titled “What is a Web Server?”A web server is software (and sometimes hardware) that listens for incoming network requests, typically over the HTTP or HTTPS protocols, sent by clients like web browsers. It processes these requests and sends back responses, often in the form of HTML documents, JSON data, images, stylesheets, or other resources.
Modern web servers often handle dynamic content generation. They might execute server-side code (like Node.js scripts), interact with databases, or communicate with other backend services to produce a tailored response for the client.
While popular dedicated web servers like Nginx or Apache exist, Node.js allows you to build your own web server directly within your application code using its built-in http module.
Typical Web Application Architecture
Section titled “Typical Web Application Architecture”Web applications often follow a layered architecture:
- Client: The user interface, usually running in a web browser or a native mobile application. It sends requests to the server.
- Server (Web Layer): This layer, often built with Node.js and potentially a framework like Express, receives client requests, handles routing, performs initial validation, and coordinates with the business logic.
- Business Logic: Contains the core application logic, rules, and processing. It interacts with the data layer to fulfill requests.
- Data Layer: Manages data persistence, typically involving databases (SQL or NoSQL) or other data stores.
Node.js typically operates in the Server (Web Layer) and can also implement the Business Logic, especially in smaller applications or microservices.
Creating a Basic Web Server using Node.js
Section titled “Creating a Basic Web Server using Node.js”Node.js provides the built-in http module to create HTTP servers and clients. Here’s a minimal example of an HTTP server that listens on port 3000 and responds with ‘Hello World!’.
Create a file named server.js:
File: server.js
// Import the built-in http moduleconst http = require('http');
const hostname = '127.0.0.1'; // Standard loopback interface address (localhost)const port = 3000;
// Create the server// The createServer method takes a callback function that is executed// for each incoming request. This function receives two arguments:// req: The request object (incoming message)// res: The response object (server response)const server = http.createServer((req, res) => { console.log(`Request received for URL: ${req.url} with method: ${req.method}`);
// Set the status code to 200 (OK) res.statusCode = 200;
// Set the Content-Type header to plain text res.setHeader('Content-Type', 'text/plain');
// Write the response body res.end('Hello World!\n');});
// Start listening for incoming connectionsserver.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`);});Explanation:
Section titled “Explanation:”require('http'): Loads the Node.js HTTP module.http.createServer((req, res) => { ... }): Creates an HTTP server instance. The callback function provided is the request listener, executed each time a request hits the server.req(Request): An object containing information about the incoming request, such as headers (req.headers), URL (req.url), and HTTP method (req.method).res(Response): An object used to send back the desired response to the client. You set headers (res.setHeader), status codes (res.statusCode), and the response body (res.end).res.end('Hello World!\n'): Sends the response body (‘Hello World!’) and signals that the response is complete.server.listen(port, hostname, () => { ... }): Tells the server to start listening for connections on the specified port and hostname. The callback function is executed once the server has successfully started.
Now, run the server from your terminal:
$ node server.jsVerify the Output in the terminal:
Server running at http://127.0.0.1:3000/Make a request to the Node.js server:
Open your web browser and navigate to http://127.0.0.1:3000/. You should see the text “Hello World!” displayed.
Check the server terminal again. You should see a log message indicating that a request was received:
Request received for URL: / with method: GETCreating an HTTP Client using Node.js
Section titled “Creating an HTTP Client using Node.js”The http module can also be used to make HTTP requests to other servers. While often done using higher-level libraries like axios or the built-in fetch API (available globally in recent Node.js versions), here’s how you can use the http module directly.
Create a file named client.js (ensure server.js is still running):
File: client.js
const http = require('http');
const options = { hostname: '127.0.0.1', port: 3000, path: '/', method: 'GET'};
// Make the requestconst req = http.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
// Set encoding for the response data res.setEncoding('utf8');
let responseBody = '';
// Data is received in chunks res.on('data', (chunk) => { responseBody += chunk; console.log(`BODY CHUNK: ${chunk}`); });
// The 'end' event signifies the entire response has been received res.on('end', () => { console.log('\n--- Response Complete ---'); console.log(responseBody); console.log('No more data in response.'); });});
// Handle potential errors during the requestreq.on('error', (e) => { console.error(`Problem with request: ${e.message}`);});
// End the request (important!) - this sends the requestreq.end();Run client.js in a separate terminal window:
$ node client.jsVerify the Client Output. You should see the status code, headers, and the ‘Hello World!’ body received from the server:
STATUS: 200HEADERS: {"content-type":"text/plain","date":"...","connection":"...","transfer-encoding":"chunked"}BODY CHUNK: Hello World!
--- Response Complete ---Hello World!
No more data in response.Verify the Server Output. You will see another log message in the server.js terminal indicating the request from client.js was received.
While the http module is fundamental, building complex web applications often involves using frameworks like Express, Koa, or Fastify, which provide abstractions and utilities for routing, middleware, request/response handling, and more.