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
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.
The HTTP module extends two built-in classes:
To get started, create a JavaScript file on your machine (e.g. app.js) and import the HTTP module.
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).
//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
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!
Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…
MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…
In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…
Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…
The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…
Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…