DEV Community

Cover image for # HTTP Client–Server Communication in Node.js: How It Works
sudip khatiwada
sudip khatiwada

Posted on

# HTTP Client–Server Communication in Node.js: How It Works

Understanding HTTP client-server communication is fundamental to building web applications with Node.js. Whether you're creating REST APIs, microservices, or full-stack applications with the MERN stack, knowing how Node.js handles HTTP requests and responses under the hood is crucial.

In this guide, we'll explore how Node.js facilitates HTTP communication between clients and servers using the built-in http module. We'll walk through practical code examples that demonstrate the complete request-response cycle.

What is HTTP Client-Server Communication?

HTTP (Hypertext Transfer Protocol) follows a client-server model where:

  • The client initiates requests to fetch or send data
  • The server listens for incoming requests and sends back responses

Node.js provides a powerful http module that allows you to create both HTTP servers and clients without external dependencies.

Building an HTTP Server in Node.js

Let's start by creating a basic HTTP server that listens for incoming requests:

import http from 'node:http';

const server = http.createServer((req, res) => {
    console.log("got the request");
    console.log(req.method);
    console.log(req.url);

    req.on("data", (chunk) => {
        console.log(chunk.toString());
    });

    res.end("Hello from HTTP Server");
});

server.listen(80, "0.0.0.0", () => {
    console.log("Server is listening on port 80");
});
Enter fullscreen mode Exit fullscreen mode

How the Server Works

1. Creating the Server:

http.createServer() creates a server instance. The callback function receives two objects: req (incoming request) and res (outgoing response).

2. Request Handling:

When a request arrives, the server logs the HTTP method (GET, POST, etc.) and the requested URL path. The req.on("data") event listener captures the request body as chunks of data.

3. Sending Response:

res.end() sends the response back to the client and closes the connection.

4. Starting the Server:

server.listen() binds the server to port 80 on all network interfaces (0.0.0.0), making it accessible from any IP address on your network.

Creating an HTTP Client in Node.js

Now let's create a client that sends a POST request to our server:

import http from 'http';

const clientRequest = http.request({
    method: "POST",
    hostname: "localhost",  
    port: 80,               
    path: "/"               
});

clientRequest.write("Hi i am client");

clientRequest.on("response", (response) => {
    response.on("data", (chunk) => {
        console.log(chunk.toString());
    });
});

clientRequest.end();
Enter fullscreen mode Exit fullscreen mode

How the Client Works

1. Configuring the Request:

http.request() creates a client request with configuration options specifying the HTTP method, target hostname, port, and path.

2. Writing Request Body:

clientRequest.write() adds data to the request body. This is particularly useful for POST or PUT requests where you need to send data to the server.

3. Handling Response:

The "response" event fires when the server responds. The response object emits "data" events for each chunk of response data received.

4. Finalizing the Request:

clientRequest.end() signals that the request is complete and should be sent to the server.

The Complete Communication Flow

When you run both pieces of code together, here's what happens:

  1. The server starts listening on port 80
  2. The client creates a POST request to localhost:80
  3. The client sends "Hi i am client" in the request body
  4. The server receives the request and logs the method, URL, and body
  5. The server responds with "Hello from HTTP Server"
  6. The client receives and logs the server's response

This pattern forms the foundation of HTTP networking in Node.js, enabling everything from simple API calls to complex microservice architectures.

Key Takeaways

  • Node.js provides native HTTP client-server capabilities through the http module
  • Servers use http.createServer() to handle incoming requests
  • Clients use http.request() to send HTTP requests
  • Both requests and responses are stream-based, using event listeners to handle data chunks
  • Understanding this low-level communication helps you work more effectively with frameworks like Express.js

Whether you're building REST APIs for your MERN stack application or creating custom networking solutions, mastering HTTP client-server communication in Node.js gives you the foundation to build robust, scalable applications.

Top comments (0)