How does Node.js handle HTTP requests?
1. Definition
Node.js handles HTTP requests using its built-in http module. It creates a server that listens for incoming client requests and sends responses back to the client.
2. Request Handling Flow
- Client sends HTTP request (browser, API call)
- Server receives request using createServer()
- Callback function processes request
- Response is sent using res.end()
3. Example
const http = require("http");
const server = http.createServer((req, res) => {
// Request info
console.log(req.method);
console.log(req.url);
// Response
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Request received");
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});4. Key Objects
- req (Request): Contains client request data
- res (Response): Used to send response to client
5. Handling Multiple Requests
- Uses event-driven architecture
- Non-blocking I/O operations
- Event loop handles multiple requests efficiently
6. Advantages
- Handles multiple requests efficiently
- Non-blocking and fast
- Scalable for real-time applications
- Lightweight server setup