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:
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:
Sends the response body.
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.
