The HTTP module in Node.js allows you to create web servers. It is the foundation of backend development and is used to handle client requests and send responses.
With just a few lines of code, you can build your own server without any framework.
1. What is HTTP Module?
The http module is a built-in Node.js module used to create servers and handle HTTP requests and responses.
const http = require("http");
2. Creating Your First Server
const http = require("http");
const server = http.createServer((req, res) => {
res.write("Hello World");
res.end();
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Open your browser: http://localhost:3000
3. Understanding the Code
- createServer() → Creates server
- req → Request
- res → Response
- res.write() → Send data
- res.end() → End response
4. Handling Routes
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.end("Home Page");
} else if (req.url === "/about") {
res.end("About Page");
} else {
res.end("404 Not Found");
}
});
5. Setting Response Headers
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello Node.js");
The HTTP module is powerful but basic. For large apps, use Express.js.
Conclusion
Now you can create your own web server using Node.js.
Your Hero to Zero Node.js journey just created a server 🌐🚀
Tags
NodeJS