Open In App

NodeJS HTTP Module

Last Updated : 06 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In NodeJS, the HTTP module is a core built-in module that enables developers to create and manage HTTP servers. It plays a crucial role in handling server-side HTTP requests and responses, allowing for seamless communication between clients and servers.

In this article, we will dive into the NodeJS HTTP module, explaining its syntax, and usage, and providing practical examples to help you understand its functionality.

What is an HTTP Module?

The NodeJS HTTP module allows you to create web servers and handle HTTP requests and responses, making it a fundamental part of building web applications in NodeJS. HTTP is the built-in module in NodeJs through which the data is transferred.

  • Uses the require() method to include the HTTP module.
  • It provides utilities to create both client and server applications.
  • Supports various HTTP methods like GET, POST, PUT, DELETE, etc.
  • Allows ease in handling request headers, query parameters, and response bodies.

Syntax

const http = require('http');

Some of the key features of the NodeJS HTTP Modules are mentioned below:

  • Server Creation: It allows the creation of HTTP servers.
  • Handling Requests: It listens for incoming HTTP requests and performs actions based on the request type.
  • Sending Responses: It sends responses back to the client, allowing for dynamic content delivery.
  • Working with Different HTTP Methods: It supports GET, POST, PUT, DELETE, and other HTTP request methods.

Creating Servers using HTTP

You can create a server using http.createServer() that listens for requests.

const http = require('http');

http.createServer((request, response) => {
    response.write('Hello World!');
    response.end();
}).listen(3000);

console.log("Server started on port 3000");

Output

Screenshot-2025-03-04-154548

Creating Server

In this example

  • http.createServer() is used to create a new HTTP server.
  • The (request) object represents the incoming request from the client.
  • The (response) object is used to send the HTTP response to the client.
  • response.write() sends data as part of the response.
  • response.end() signals that the response is complete.
  • server.listen() makes the server listen on the specified port (3000 in this case).

Adding an HTTP Header

Adding an HTTP header, especially the Content-Type header, helps inform the client (usually the browser) about the type of content the server is sending. This is important for proper rendering of the response.

  • If the Content-Type is set to text/html, the browser knows that the response is an HTML document and can render it accordingly.
  • If the Content-Type is set to application/json, the browser or client knows the response is in JSON format and can parse it as such.
var http = require('http');
var url = require('url');

http.createServer(function (req, res) {
    var q = url.parse(req.url, true).query; // Parse the query string
    var contentType = 'text/html';

    if (q.json === 'true') {
        contentType = 'application/json';
    }

    res.writeHead(200, { 'Content-Type': contentType });

    if (contentType === 'text/html') {
        res.write('<html><body><h1>Hello, World!</h1></body></html>');
    } else if (contentType === 'application/json') {
        res.write(JSON.stringify({ message: "Hello, World!" }));
    }
    res.end();
}).listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

Output

Animationkk

In this example

  • When you visit http://localhost:3000/, the server will respond with an HTML page.
  • The HTTP header will be set as Content-Type: text/html.
  • The browser knows to render the response as an HTML document.
  • If you visit http://localhost:3000/?json=true, the server will respond with a JSON object.
  • The HTTP header will be set as Content-Type: application/json.
  • The browser or client knows to treat the response as a JSON object and can handle it accordingly (e.g., parsing it in JavaScript).Reading the Query String

Reading the Query String

The http.createServer() function takes a request (req) object, which contains information about the incoming HTTP request. One of the key properties of the req object is url, which holds the part of the URL after the domain name.

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write(req.url);
    res.end();
}).listen(8080, () => {
    console.log('Server running at http://localhost:8080/');
});

Output

Animationkk

Reading the query string

In this example

  • http://localhost:8080/name will display /name
  • http://localhost:8080/summer will display /summer
  • The server listens for HTTP requests.
  • req.url returns the full URL requested by the client, including the path and query string (if any).
  • The server sends the path (including any query string) as part of the response.

Splitting the Query String

You can use the built-in url module to easily parse and split the query string into readable parts.

var http = require('http');
var url = require('url');

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    var q = url.parse(req.url, true).query; // Parse the query string
    var txt = q.year + " " + q.month; // Get year and month from query string
    res.end(txt); // Display the result
}).listen(8080, () => {
    console.log('Server running at http://localhost:8080/');
});

Output

Animationkk

In this example

  • The server listens for HTTP requests and parses the query string of the URL.
  • The url.parse(req.url, true).query parses the URL and extracts the query parameters as an object.
  • The q.year and q.month are then concatenated into a string txt.
  • The server sends the txt string (2025 March) as the response, if you access the URL:
http://localhost:8080/?year=2025&month=March
  • If no query parameters are provided, the output will be undefined undefined.

Conclusion

The HTTP module in NodeJS is an essential tool for building web servers and handling HTTP requests and responses. With this module, you can:

  • Create a basic HTTP server.
  • Handle different HTTP methods like GET, POST, etc.
  • Work with URL parameters and query strings.

NodeJS HTTP Module – FAQs

What is the NodeJS HTTP module used for?

The NodeJS HTTP module is used to create and manage web servers and handle HTTP requests and responses.

How do you create a simple HTTP server in NodeJS?

You can create a simple HTTP server using the http.createServer() method, which listens to server ports and sends a response back to the client.

What are the key features of the NodeJS HTTP module?

The HTTP module allows for the creation of HTTP servers, handling of various HTTP methods, headers, and data streams, and eliminates the need for external libraries to handle HTTP in NodeJS.

How can you handle different HTTP methods in NodeJS using the HTTP module?

By examining the req.method property within the server callback function, you can implement logic to handle different HTTP methods such as GET, POST, PUT, and DELETE.

Is it possible to make HTTP requests to other servers using the NodeJS HTTP module?

Yes, the HTTP module provides methods like http.request() and http.get() to send HTTP requests to other servers and handle their responses.



Next Article

Similar Reads

three90RightbarBannerImg