Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Building a Web Server with Node.js HTTP Module

Tech 3

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:

  1. Import the HTTP module.
  2. Instantiate a server object.
  3. Bind a listener to the request event to handle incoming client requests.
  4. 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');
});
Tags: nodejshttp

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.