Learn Node.js · 5/13

Building Web Servers: The Native Node.js Way

7 min read

Welcome, intrepid coder, to the world of building web servers with nothing but the power of Node.js itself! While frameworks like Express are fantastic tools, understanding the underlying http module is like learning how a car engine works before you start adding turbochargers. It gives you a deeper appreciation and control over your web applications.

So, buckle up! We're about to go on a journey from spinning up a simple server to handling different types of data and routing requests like a seasoned pro.

The 'http' Module: Spinning Up a Basic Server 🚀

At the very core of Node.js's web capabilities lies the built-in http module. This powerful little module contains all the necessary tools to create an HTTP server. Think of it as your foundational toolkit for anything web-related in Node.js.

The Problem: You need a way for your application to listen for incoming requests from the internet (like a user visiting a webpage in their browser) and send back a response.

The Solution: The http module provides a createServer() method. This method takes a callback function that will be executed every time a request is received.

Let's see it in action. Here is the "Hello, World!" of Node.js web servers:

javascript
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

To run this, save it as a file (e.g., server.js) and execute node server.js in your terminal. Open your web browser and navigate to http://127.0.0.1:3000, and you should see "Hello World" proudly displayed.

🧐 Let's break that down:

  • const http = require('http');: We start by importing the built-in http module.
  • http.createServer((req, res) => { ... });: This is the star of the show. It creates a new server object. The function we pass to it is our request handler. It gets called every single time a request hits our server.
  • req and res: These are two very important objects that are automatically passed to our request handler. We'll dive deeper into them shortly.
  • res.statusCode = 200;: We set the HTTP status code to 200, which means "OK".
  • res.setHeader('Content-Type', 'text/plain');: We're telling the browser what kind of content we're sending back. In this case, it's plain text.
  • res.end('Hello World');: This sends the response body and signals to the server that the response is complete.
  • server.listen(port, hostname, () => { ... });: This tells our server to start listening for incoming connections on the specified port and hostname. The callback function is executed once the server has successfully started.

Fun Fact: Every time you visit a website, your browser is making an HTTP request to a server, and that server is sending back an HTTP response. Our little Node.js script is doing exactly that!

Understanding the Request and Response Objects 🕵️‍♀️

The req (request) and res (response) objects are your primary tools for handling incoming requests and sending back data. They are passed as arguments to the callback function of http.createServer().

The Request Object (req)

The request object represents the incoming HTTP request from the client (e.g., a web browser). It contains a wealth of information about the request. Think of it as a detailed order ticket in a restaurant. It tells you what the customer wants.

Here are some of the most frequently used properties of the req object:

  • req.url: This contains the URL path that was requested. For example, if a user visits http://your-server.com/about, req.url will be /about.
  • req.method: This tells you the HTTP method of the request, such as GET, POST, PUT, or DELETE.
  • req.headers: This is an object containing the HTTP headers sent with the request. Headers provide additional information about the request, like the user's browser (User-Agent) or the types of content the browser can accept (Accept).

The Response Object (res)

The response object is what you use to send a response back to the client. It's like the plate you use to send the food back to the customer.

Here are some of the most common methods on the res object:

  • res.writeHead(statusCode, headers): This sends the response headers to the client. statusCode is a three-digit HTTP status code (e.g., 200 for success, 404 for not found). headers is an object of key-value pairs representing the response headers.
  • res.write(chunk): This sends a chunk of the response body. You can call this multiple times to send the response in pieces.
  • res.end([data]): This method signals that all of the response headers and body have been sent; that server should consider this message complete. The data argument is optional and can be used to send the last part of the response body.

Basic Routing Without Frameworks 🗺️

The Problem: Your server needs to respond differently based on the URL the user is visiting. For example, you want to show a "Welcome" message on the homepage (/) and an "About Us" page on /about.

The Solution: You can use the req.url property to check which path the user is requesting and then send the appropriate response. This is the fundamental concept behind routing.

Let's expand our server to handle some basic routing:

javascript
const http = require('http');

const server = http.createServer((req, res) => {
  const { url } = req; // A little destructuring to make it cleaner

  if (url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Welcome to our homepage!');
  } else if (url === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('This is our about page.');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('404 Not Found');
  }
});

server.listen(3000, () => {
  console.log('Server is listening on http://localhost:3000');
});

Now, if you run this server and visit http://localhost:3000, you'll see the homepage message. If you go to http://localhost:3000/about, you'll get the about page content. And for any other URL, you'll see a "404 Not Found" error.

This is a very simple routing system, but it demonstrates the core principle. As your application grows, you might want to use a more sophisticated routing solution, which is where frameworks like Express really shine. But for now, you're doing it all by hand!

Serving Different Data Types: JSON vs. HTML 📄

So far, we've only been sending plain text. But web servers usually need to send other types of data, most commonly HTML to structure web pages and JSON for APIs.

The Problem: You need to tell the browser what kind of data you're sending so it can render it correctly.

The Solution: The Content-Type header is your best friend here. It tells the browser how to interpret the response body.

Serving JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It's very common for APIs to return data in JSON format.

javascript
const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/api/data') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    const data = {
      name: 'John Doe',
      age: 30,
      email: '[email protected]'
    };
    res.end(JSON.stringify(data));
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

server.listen(3000, () => {
  console.log('Server is listening on http://localhost:3000');
});

In this example, when a user visits /api/data, we set the Content-Type to application/json. Then, we create a JavaScript object and use JSON.stringify() to convert it into a JSON string before sending it in the response.

Serving HTML

To send an HTML page, you'll set the Content-Type to text/html.

javascript
const http = require('http');
const fs = require('fs'); // We'll need the file system module to read an HTML file

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    fs.readFile('index.html', (err, data) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Error loading index.html');
      } else {
        res.end(data);
      }
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

server.listen(3000, () => {
  console.log('Server is listening on http://localhost:3000');
});

And in a file named index.html in the same directory:

html
<!DOCTYPE html>
<html>
<head>
  <title>My Awesome Page</title>
</head>
<body>
  <h1>Welcome to my HTML page!</h1>
</body>
</html>

Here, we're using the built-in fs module to read the contents of index.html. Once the file is read, we send its content as the response body with the Content-Type set to text/html.

📜 Extra Reading & References

Challenge

You are tasked with building a dynamic web server using Node.js's native http module. The server must handle different routes, HTTP methods, and content types.

Your server should perform the following actions:

  1. Create an HTTP server that listens on hostname 127.0.0.1 and port 3000.
  2. Implement routing based on the request URL (req.url) and method (req.method):
    • Route GET /:
      • Respond with a status code of 200.
      • Set the Content-Type header to text/html.
      • Send the following HTML string as the response body: <h1>Welcome to the Homepage</h1>.
    • Route GET /api/user:
      • Respond with a status code of 200.
      • Set the Content-Type header to application/json.
      • Send a JSON response representing a user object: { "user": { "id": 1, "name": "John Doe" } }.
    • Route POST /api/user:
      • Respond with a status code of 201.
      • Set the Content-Type header to text/plain.
      • Send the plain text message: User created successfully.
    • For any other route not listed above:
      • Respond with a status code of 404.
      • Set the Content-Type header to text/plain.
      • Send the plain text message: 404 Not Found.

Complete the code within the http.createServer callback to implement this logic.

Expected result

Your code should correctly implement the request handling logic inside the http.createServer callback. The solution involves using conditional statements to check both req.url and req.method to determine the appropriate response.

A correct implementation would look like this:

javascript
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  if (req.url === '/' && req.method === 'GET') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end('<h1>Welcome to the Homepage</h1>');
  } else if (req.url === '/api/user' && req.method === 'GET') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ user: { id: 1, name: 'John Doe' } }));
  } else if (req.url === '/api/user' && req.method === 'POST') {
    res.statusCode = 201;
    res.setHeader('Content-Type', 'text/plain');
    res.end('User created successfully');
  } else {
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/plain');
    res.end('404 Not Found');
  }
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

The key aspects are:

  • Using req.url and req.method to create distinct routes.
  • Setting the correct statusCode for each response (200 for OK, 201 for Created, 404 for Not Found).
  • Setting the appropriate Content-Type header (text/html, application/json, text/plain).
  • Using JSON.stringify() to convert the JavaScript object to a JSON string before sending.
  • Calling res.end() to send the response body and finalize the response.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.