HTTP Module
Thehttp module allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP). It is the foundation for web servers in Node.js.
Creating a Server
Thehttp.createServer() method includes a request listener function which is automatically added to the 'request' event.
http://localhost:5000 in your browser.
The Request and Response Objects
The callback function receives two arguments:req(Request): Contains information about the incoming request (URL, method, headers, etc.).res(Response): Used to send a response back to the client.
Inspecting the Request
Setting Headers and Status Code
Basic Routing
You can usereq.url to handle different routes.
Serving JSON
To serve an API, you typically return JSON data.Serving HTML Files
To serve actual HTML files, we combine thehttp module with the fs module.
Handling POST Requests
Unlike GET requests, POST data comes in chunks and must be collected:Query Parameters
Headers Deep Dive
Request Headers
Response Headers
Building a Simple Router
HTTPS Server
For production, you need HTTPS:Summary
- The
httpmodule creates web servers without external dependencies - Use
req.urlandreq.methodfor routing - POST data arrives in chunks via
'data'and'end'events - Parse query strings with the
URLclass - Set appropriate Content-Type headers for responses
- Build custom routers for organized code
- Use
httpsmodule with SSL certificates for production - Frameworks like Express.js abstract this complexity