Creating an HTTP Server in Node.js
Node.js allows us to create an HTTP server using its built-in
http module. The server listens for client requests,
processes them, and sends responses back to the client.
1. What is an HTTP Server?
An HTTP server receives HTTP requests from clients such as web browsers
and sends HTTP responses. In Node.js, we can create a basic server
using http.createServer().
Imagine Samadhan opens the CIIT Training Institute website. His browser sends a request to the server. The server processes the request and returns a response that the browser can display.
2. Import the HTTP Module
First, import the built-in http module.
We do not need to install an additional npm package for it.
const http = require("http");
console.log("HTTP module imported successfully.");
Output
HTTP module imported successfully.
Explanation
require("http")loads the Node.js HTTP module.- The imported module is stored in the
httpvariable. - We use this object to create an HTTP server.
3. Creating a Basic HTTP Server
The http.createServer() method creates an HTTP server.
Its callback receives two objects: req and res.
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Welcome to CIIT Training Institute!");
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
Terminal Output
Server running at http://localhost:3000
Browser Output
Explanation
http.createServer()creates the server.reqrepresents the incoming request.resrepresents the outgoing response.res.end()sends the response body and completes the response.server.listen(3000)starts listening on port 3000.
4. HTTP Server Request–Response Flow
5. Setting Status Code and Headers
We can use res.writeHead() to set the HTTP status code
and response headers. For example, status code 200 indicates success.
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Hello Samadhan! Your server is working.");
});
server.listen(3000, () => {
console.log("Server started on port 3000");
});
Browser Output
Explanation
200is the HTTP success status code.Content-Typetells the client how to interpret the response body.text/plainindicates that the response contains plain text.res.end()completes the response.
6. Sending an HTML Response
An HTTP server can also return HTML. Set the content type to
text/html so the browser interprets the response as HTML.
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8"
});
res.end(`
<h1>CIIT Training Institute</h1>
<p>Welcome, Pradnya!</p>
`);
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Browser Output
CIIT Training Institute
Welcome, Pradnya!
7. HTTP Server Lifecycle
8. How to Run the Server
- Create a JavaScript file named
server.js. - Paste one of the server examples into the file.
- Open a terminal in the same directory.
- Run the following command.
node server.js
Open this address in your browser:
http://localhost:3000
9. Understanding Request and Response Objects
| Object / Method | Purpose |
|---|---|
req |
Contains information about the incoming request. |
res |
Used to construct and send the response. |
http.createServer() |
Creates an HTTP server. |
server.listen() |
Starts listening for client connections. |
res.writeHead() |
Sets the status code and response headers. |
res.write() |
Writes part of the response body. |
res.end() |
Completes the response. |
10. Common Mistakes
| Mistake | Correct Approach |
|---|---|
Forgetting server.listen(). |
Start listening on an available port. |
Forgetting res.end(). |
Complete the response when all response data has been sent. |
| Using the wrong content type. | Choose a content type that matches the response, such as text/plain or text/html. |
| Starting multiple servers on the same port. | Stop the old server or select another available port. |
| Confusing terminal output with browser output. | Use console.log() for terminal messages and res.end() for the HTTP response. |
11. Important Points to Remember
- The HTTP module is built into Node.js.
http.createServer()creates the server.- The request handler receives
reqandres. server.listen()starts listening on a port.res.writeHead()sets the response status and headers.res.end()completes the response.- The browser can display plain text, HTML, or other supported response formats.
Summary
In this lesson, we learned how to create an HTTP server in Node.js, import the HTTP module, handle incoming requests, send text and HTML responses, set status codes and headers, and start a server using server.listen(). Examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate the basic server workflow.