Node.js, known for its asynchronous and event-driven architecture, offers a multitude of built-in modules that make it easy to build scalable and fast web applications. Among these modules, the HTTP module is one of the most crucial as it allows you to create web servers and handle requests and responses effortlessly.
In this blog, we’ll explore the fundamentals of the Node.js HTTP module, including how to set up a basic web server, handle different HTTP methods, and work with headers and status codes.
Contents
Introduction to Node.js HTTP Module
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the HyperText Transfer Protocol (HTTP) as well as communicate with other APIs using HTTP 1.1, HTTP 2, and HTTPS.
Architecture of Node.js HTTP Module
The HTTP module extends two built-in classes:
- Net module – Provides network API for creating stream-based TCP servers or clients.
- Events module – Provides an event-driven architecture using EventEmitter class.
Simple Server
To get started, create a JavaScript file on your machine (e.g. app.js) and import the HTTP module.
1 2 |
const http = require('http') const server = http.createServer((req, res) => { ... }); |
The function takes two arguments: request object (req), response object (res). Both arguments are stream objects. After creating a server, set a response in the handler (callback function).
1 2 3 4 5 6 7 8 9 10 |
//create a server object: http.createServer(function (req, res) { res.write('Hello World!'); //write a response to the client res.end(); //end the response }).listen(8080); //the server object listens on port 8080 server.listen(3000, () => { console.log('Server started on localhost:3000!'); }) |
If you run this file (using node app.js), you should see a message
Server started on localhost:3000! printed in the console.
Open a web browser, head over to localhost:3000 and you should see the response from the server displayed in the browser
Conclusion
The Node.js HTTP module is a powerful and flexible tool that allows developers to handle web requests with ease. From setting up simple servers to handling different HTTP methods and working with headers, the HTTP module gives you complete control over how you build web applications.
Whether you’re building a basic website or a full-fledged API, understanding the HTTP module in Node.js is a fundamental step in becoming a proficient backend developer.
Happy Coding!