# Node.js HTTP Module – Building My First Server

# 🔹 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:

```text
example.com
```

your browser communicates with a server using HTTP.

A simplified flow:

```text
Client
  ↓
HTTP Request
  ↓
Server
  ↓
HTTP Response
  ↓
Client
```

* * *

# 🔹 Client vs Server

The **client** is usually the application making the request.

For example:

```text
Browser
React App
Mobile App
Postman
```

The **server** receives the request and decides what to do.

```text
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:

```text
http
```

We don't need to install it.

We can import it:

```js
import http from "http";
```

The `http` module allows us to create HTTP servers.

* * *

# 🔹 Creating Our First Server

Let's create:

```text
server.js
```

Add:

```js
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:

```bash
node server.js
```

You'll see:

```text
Server running on port 5000
```

Now open:

```text
http://localhost:5000
```

You should receive:

```text
Hello from Node.js!
```

🎉 **You just created your first HTTP server with Node.js.**

* * *

# 🔹 Understanding `createServer()`

This:

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

creates an HTTP server.

The callback receives two important objects:

```text
request
response
```

### `request`

Contains information about what the client is asking for.

### `response`

Used to send information back to the client.

Think:

```text
Request
   ↓
Server
   ↓
Response
```

* * *

# 🔹 The Request Object

Let's inspect the request.

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

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

Visit:

```text
http://localhost:5000/users
```

You might see:

```text
GET
/users
```

The request gives us useful information such as:

```text
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:

```text
GET /users
```

means:

> Give me users.

While:

```text
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:

```text
GET /users
GET /products
POST /users
DELETE /users/10
```

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

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

Now:

```text
/ 
```

returns:

```text
Home Page
```

* * *

# 🔹 Creating Multiple Routes

Let's build a small API.

```js
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:

```text
/          → 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:

```js
response.statusCode = 404;

response.end("User not found");
```

The client receives:

```text
404 Not Found
```

* * *

# 🔹 Setting Response Status

For a successful response:

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

For a created resource:

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

* * *

# 🔹 Response Headers

HTTP responses can contain headers.

For example:

```js
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:

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

We can return it as JSON:

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

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

The client receives:

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

This is the foundation of REST APIs.

* * *

# 🔹 Building a Small JSON API

Let's combine everything.

```js
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:

```text
GET /users
```

which returns JSON.

* * *

# 🔹 Why `return` Is Useful

Notice:

```js
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:

```js
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:

```js
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:

```text
Request Body
     ↓
Chunk
     ↓
Chunk
     ↓
Chunk
     ↓
"end"
```

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

* * *

# 🔹 JSON Request Body

Suppose Postman sends:

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

We can parse it:

```js
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:

```text
GET
http://localhost:5000/users
```

Or:

```text
POST
http://localhost:5000/users
```

with JSON:

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

This allows you to test the backend before connecting React.

* * *

# 🔹 What We've Built

At this point:

```text
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:

```text
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:

```text
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:

```text
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.
