Skip to main content

Command Palette

Search for a command to run...

Node.js HTTP Module โ€“ Building My First Server

Updated
โ€ข8 min readโ€ขView as Markdown

๐Ÿ”น What Is HTTP?

HTTP stands for:

HyperText Transfer Protocol

It's the protocol commonly used for communication between clients and servers on the web.

For example, when you visit:

example.com

your browser communicates with a server using HTTP.

A simplified flow:

Client
  โ†“
HTTP Request
  โ†“
Server
  โ†“
HTTP Response
  โ†“
Client

๐Ÿ”น Client vs Server

The client is usually the application making the request.

For example:

Browser
React App
Mobile App
Postman

The server receives the request and decides what to do.

Client
   โ†“
Request
   โ†“
Node.js Server
   โ†“
Logic
   โ†“
Response

This is the basic foundation of backend development.


๐Ÿ”น Node.js http Module

Node.js provides a built-in module called:

http

We don't need to install it.

We can import it:

import http from "http";

The http module allows us to create HTTP servers.


๐Ÿ”น Creating Our First Server

Let's create:

server.js

Add:

import http from "http";

const server = http.createServer((request, response) => {
  response.end("Hello from Node.js!");
});

server.listen(5000, () => {
  console.log("Server running on port 5000");
});

Run:

node server.js

You'll see:

Server running on port 5000

Now open:

http://localhost:5000

You should receive:

Hello from Node.js!

๐ŸŽ‰ You just created your first HTTP server with Node.js.


๐Ÿ”น Understanding createServer()

This:

http.createServer((request, response) => {
});

creates an HTTP server.

The callback receives two important objects:

request
response

request

Contains information about what the client is asking for.

response

Used to send information back to the client.

Think:

Request
   โ†“
Server
   โ†“
Response

๐Ÿ”น The Request Object

Let's inspect the request.

const server = http.createServer((request, response) => {
  console.log(request.method);
  console.log(request.url);

  response.end("Request received");
});

Visit:

http://localhost:5000/users

You might see:

GET
/users

The request gives us useful information such as:

request.method
request.url
request.headers

๐Ÿ”น HTTP Methods

HTTP requests commonly use different methods depending on what we're trying to do.

Method Common Purpose
GET Retrieve data
POST Create data
PUT Replace data
PATCH Partially update data
DELETE Delete data

For example:

GET /users

means:

Give me users.

While:

POST /users

generally means:

Create a user.


๐Ÿ”น Routes

A route is essentially a combination of a path and HTTP method that determines what the server should do.

For example:

GET /users
GET /products
POST /users
DELETE /users/10

With Node's basic HTTP module, we can manually check the URL and method.

const server = http.createServer((request, response) => {
  if (
    request.method === "GET" &&
    request.url === "/"
  ) {
    response.end("Home Page");
  }
});

Now:

/ 

returns:

Home Page

๐Ÿ”น Creating Multiple Routes

Let's build a small API.

import http from "http";

const server = http.createServer((request, response) => {
  if (
    request.method === "GET" &&
    request.url === "/"
  ) {
    response.end("Welcome");
  }

  else if (
    request.method === "GET" &&
    request.url === "/users"
  ) {
    response.end("Users");
  }

  else if (
    request.method === "GET" &&
    request.url === "/products"
  ) {
    response.end("Products");
  }

  else {
    response.statusCode = 404;
    response.end("Route not found");
  }
});

server.listen(5000, () => {
  console.log("Server running...");
});

Now:

/          โ†’ Welcome
/users     โ†’ Users
/products  โ†’ Products
/random    โ†’ 404

This is a basic routing system.

And this also shows why frameworks such as Express are useful โ€” manually handling many routes quickly becomes cumbersome.


๐Ÿ”น HTTP Status Codes

Servers use status codes to communicate the result of a request.

Some important ones:

Status Meaning
200 OK
201 Created
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
500 Internal Server Error

For example:

response.statusCode = 404;

response.end("User not found");

The client receives:

404 Not Found

๐Ÿ”น Setting Response Status

For a successful response:

response.statusCode = 200;
response.end("Success");

For a created resource:

response.statusCode = 201;
response.end("User created");

๐Ÿ”น Response Headers

HTTP responses can contain headers.

For example:

response.setHeader(
  "Content-Type",
  "text/plain"
);

response.end("Hello!");

The header tells the client what kind of content it's receiving.


๐Ÿ”น Returning JSON

This is especially important for APIs.

Suppose we have:

const users = [
  {
    id: 1,
    name: "Saurabh"
  },
  {
    id: 2,
    name: "Rahul"
  }
];

We can return it as JSON:

response.setHeader(
  "Content-Type",
  "application/json"
);

response.end(JSON.stringify(users));

The client receives:

[
  {
    "id": 1,
    "name": "Saurabh"
  },
  {
    "id": 2,
    "name": "Rahul"
  }
]

This is the foundation of REST APIs.


๐Ÿ”น Building a Small JSON API

Let's combine everything.

import http from "http";

const users = [
  {
    id: 1,
    name: "Saurabh",
    role: "Developer"
  },
  {
    id: 2,
    name: "Rahul",
    role: "Designer"
  }
];

const server = http.createServer((request, response) => {

  if (
    request.method === "GET" &&
    request.url === "/users"
  ) {

    response.statusCode = 200;

    response.setHeader(
      "Content-Type",
      "application/json"
    );

    response.end(JSON.stringify(users));

    return;
  }

  response.statusCode = 404;

  response.setHeader(
    "Content-Type",
    "application/json"
  );

  response.end(
    JSON.stringify({
      message: "Route not found"
    })
  );
});

server.listen(5000, () => {
  console.log("Server running on port 5000");
});

Now we have:

GET /users

which returns JSON.


๐Ÿ”น Why return Is Useful

Notice:

response.end(JSON.stringify(users));

return;

Once we send the response, we don't want the server to continue into the fallback logic.

Without proper control flow, you can accidentally attempt to send another response.


๐Ÿ”น Understanding response.end()

This:

response.end("Hello");

does two things conceptually:

  1. Sends the response body.

  2. Signals that the response is complete.

You should make sure every handled request eventually gets an appropriate response.


๐Ÿ”น Reading POST Request Data

GET requests commonly retrieve data.

But POST requests can send data to the server.

HTTP request bodies arrive as streams of data.

For example:

if (
  request.method === "POST" &&
  request.url === "/users"
) {
  let body = "";

  request.on("data", chunk => {
    body += chunk;
  });

  request.on("end", () => {
    console.log(body);

    response.statusCode = 201;
    response.end("User received");
  });
}

The request body arrives in chunks.

Conceptually:

Request Body
     โ†“
Chunk
     โ†“
Chunk
     โ†“
Chunk
     โ†“
"end"

This is connected to Node.js's event-driven architecture.


๐Ÿ”น JSON Request Body

Suppose Postman sends:

{
  "name": "Saurabh",
  "email": "saurabh@example.com"
}

We can parse it:

request.on("end", () => {
  try {
    const user = JSON.parse(body);

    console.log(user);

    response.statusCode = 201;

    response.setHeader(
      "Content-Type",
      "application/json"
    );

    response.end(
      JSON.stringify({
        message: "User created",
        user
      })
    );

  } catch (error) {
    response.statusCode = 400;

    response.end("Invalid JSON");
  }
});

This is a very important backend concept.


๐Ÿ”น Postman

You can use Postman to test your backend.

For example:

GET
http://localhost:5000/users

Or:

POST
http://localhost:5000/users

with JSON:

{
  "name": "Saurabh",
  "email": "saurabh@example.com"
}

This allows you to test the backend before connecting React.


๐Ÿ”น What We've Built

At this point:

Postman
   โ†“
HTTP Request
   โ†“
Node.js
   โ†“
Route
   โ†“
Logic
   โ†“
HTTP Response
   โ†“
Postman

That's a real client-server interaction.


๐Ÿ”น Why Express.js Exists

Now we can understand something important.

Node's http module works.

But imagine an application with:

50 routes
Authentication
Validation
Middleware
Error handling
Cookies
Request parsing
Database operations

Managing all of that manually with http.createServer() would become difficult.

That's where Express.js comes in.

Express provides a much more convenient way to build web servers and APIs on top of Node.js.

Conceptually:

Node.js
   โ†“
HTTP Module
   โ†“
Express.js
   โ†“
REST API

So learning today's topic makes Express easier to understand.


๐Ÿ”ฅ Node.js โ†’ Express Mental Model

Think of it this way:

Node.js
   โ”‚
   โ””โ”€โ”€ Provides JavaScript runtime
           โ”‚
           โ†“
       HTTP Module
           โ”‚
           โ””โ”€โ”€ Allows HTTP servers
                   โ”‚
                   โ†“
              Express.js
                   โ”‚
                   โ”œโ”€โ”€ Routing
                   โ”œโ”€โ”€ Middleware
                   โ”œโ”€โ”€ Request handling
                   โ””โ”€โ”€ API development

Tomorrow, this becomes much easier to appreciate.

1 views

100 Days of Code: My Journey to Becoming a Full Stack Developer

Part 1 of 50

Welcome to my 100 Days of Code journey! In this series, I'll document my daily progress as I learn Full Stack Web Development from the ground up. Every post will cover what I learned, challenges I faced, mistakes I made, and the projects I built. My goal is not just to complete 100 days but to become a better developer through consistency, discipline, and learning in public. Topics I'll cover include: โ€ข Git & GitHub โ€ข HTML, CSS & JavaScript โ€ข React.js โ€ข Node.js & Express โ€ข MongoDB โ€ข APIs โ€ข Real-world Projects โ€ข AI tools for Developers Whether you're just starting out or revising your fundamentals, I hope this journey helps you learn alongside me. Let's build, learn, and grow together! ๐Ÿš€