Creating Web Servers and Handling HTTP Requests in Node.js
Node.js provides a built-in http module that allows you to create web servers and handle HTTP requests. This module is simple to use and allows you to build server-side applications without relying on external frameworks.
Creating a Simple Web Server
Here’s how to create a simple web server in Node.js using the http module:
const http = require("http");
const server = http.createServer((req, res) => { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("Hello, Node.js!");});
server.listen(3000, () => { console.log("Server running at http://localhost:3000/");});-
http.createServer(): This method creates a new HTTP server. It takes a callback function with two parameters:req(request): An object that contains information about the incoming HTTP request.res(response): An object that allows you to send a response back to the client.
-
res.writeHead(): This method sets the HTTP status code (200 OK) and the response headers (e.g.,Content-Typeset totext/plain). -
res.end(): This method sends the response back to the client. In this case, the response contains the string “Hello, Node.js!”. -
server.listen(): This method makes the server listen on a specified port (3000 in this case) and logs a message when the server is ready.
Handling HTTP Requests
You can handle different types of HTTP requests such as GET, POST, and PUT by checking the request method (req.method). Here’s how you can handle a basic GET request:
const http = require("http");
const server = http.createServer((req, res) => { if (req.method === "GET") { res.writeHead(200, { "Content-Type": "text/html" }); res.end("<h1>Welcome to the Node.js Server!</h1>"); } else { res.writeHead(405, { "Content-Type": "text/plain" }); res.end("Method Not Allowed"); }});
server.listen(3000, () => { console.log("Server running at http://localhost:3000/");});- Check
req.method: Thereq.methodproperty contains the HTTP method (e.g.,GET,POST). By checking this value, you can conditionally handle different types of requests. - Handling
GETRequest: If the request method isGET, we respond with an HTML message. - Handling Other Requests: If the request method is not
GET, we return a405 Method Not Allowedresponse.
Conclusion
- Using the
httpmodule in Node.js, you can easily create a web server and handle HTTP requests. - The
http.createServer()method is fundamental for building simple server-side applications in Node.js. - By examining the
req.methodand responding accordingly, you can handle various types of HTTP requests and return appropriate responses.