Introduction
Node.js can be used to create web servers without the need for additional software like Apache or Nginx. The built-in http
module enables us to create HTTP servers, handle requests, and send responses.
1. The HTTP Module
The http
module is a core module in Node.js used for creating and managing web servers.
To use it, we import it using:
const http = require("http");
2. Creating a Basic HTTP Server
A simple HTTP server can be created using the http.createServer()
method.
Example:
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, World!");
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Explanation:
- The server listens on port 3000.
- It sends a simple
Hello, World!
response to the client. res.writeHead(200, { "Content-Type": "text/plain" })
sets the response header.
Run the script and visit http://localhost:3000
in your browser.
3. Handling Different Request Methods
Web servers process different types of requests (GET, POST, PUT, DELETE). We can handle them using the req.method
property.
Example:
const server = http.createServer((req, res) => {
if (req.method === "GET") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("This is a GET request");
} else if (req.method === "POST") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("This is a POST request");
} else {
res.writeHead(405, { "Content-Type": "text/plain" });
res.end("Method Not Allowed");
}
});
server.listen(3000, () => console.log("Server running on port 3000"));
4. Serving HTML and JSON Responses
Serving HTML
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Welcome to Node.js Web Server</h1>");
});
server.listen(3000, () => console.log("Server running on port 3000"));
Serving JSON
const server = http.createServer((req, res) => {
const data = { message: "Hello, JSON!" };
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(data));
});
server.listen(3000, () => console.log("Server running on port 3000"));
5. Handling URL Routing
We can serve different pages based on the requested URL using req.url
.
Example:
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Home Page</h1>");
} else if (req.url === "/about") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>About Page</h1>");
} else {
res.writeHead(404, { "Content-Type": "text/html" });
res.end("<h1>404 Not Found</h1>");
}
});
server.listen(3000, () => console.log("Server running on port 3000"));
6. Using External Modules (Express.js)
For more advanced web servers, Express.js simplifies routing and request handling.
Installing Express.js:
npm install express
Creating a Basic Express Server:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello from Express!");
});
app.listen(3000, () => console.log("Express server running on port 3000"));
š Exercises
- 1. Create a Node.js web server that responds with "Hello, World!".
- 2. Modify the server to handle GET and POST requests differently.
- 3. Add URL routing to display a different message on different endpoints.
- 4. Serve an HTML page instead of plain text.
- 5. Convert the server to use Express.js and add a JSON API route.
Conclusion
This chapter introduced how to create a basic Node.js web server using the http
module, handle different HTTP requests, serve responses in various formats, and implement basic routing. In the next chapter, we will explore Express.js in more depth to build more robust APIs.