Skip to content
Related Articles

Related Articles

Node.js http.ClientRequest.connection Property
  • Last Updated : 12 Jan, 2021

The http.ClientRequest.connection is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to get the reference of underlying client request socket.

Syntax:

const request.connection

Parameters: It does not accept any argument as the parameter.

Return Value: It does not return any value.

Example 1: Filename-index.js



Javascript




// Node.js program to demonstrate the  
// request.connection method
  
// Importing http module
const http = require('http');
  
// Create an HTTP server
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('okay');
});
  
// Now that server is running
server.listen(3000, '127.0.0.1', () => {
  
    // Make a request
    const options = {
        port: 3000,
        host: '127.0.0.1',
        headers: {
            'Connection': 'Upgrade',
            'Upgrade': 'websocket'
        }
    };
  
    // Getting client request
    const req = http.request(options);
  
    // Getting request socket
    // by using connection method
    const v = req.connection;
  
    // Display the result
    console.log("request socket :- " + v)
  
    process.exit(0)
});

Run the index.js file using the following command:

node index.js

Output:

request socket :- null

Example 2: Filename-index.js

Javascript




// Node.js program to demonstrate the  
// request.connection method
  
// Importing http module
const http = require('http');
  
// Create an HTTP server
http.createServer((req, res) => { })
.listen(3000, '127.0.0.1', () => {
  
    // Getting clinet request
    const req = http.request({
        port: 3000,
        host: '127.0.0.1',
    });
  
    // Getting request socket
    // by using connection method
    if (req.connection) {
        console.log("Requested for Connection")
    } else {
        console.log("Not Requested for Connection")
    }
  
    process.exit(0)
});

Run the index.js file using the following command:

node index.js

Output:

Not Requested for Connection

Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_connection

My Personal Notes arrow_drop_up
Recommended Articles
Page :