What is the Node request property "connection"?
Overview
In this shot, we will learn about the request property connection, which is a property similar to the socket property.
The request.connection property returns all the details of the connection between the server and the client, and the object has details like localAddress, socket.writable, socket.readable, etc.
Code
Let’s try to use request.connection and get all the connection details created.
const http = require('http')const port = 8080const server = http.createServer((req,res)=>{res.statusCode = 400;res.end();});const listener= server.listen(port, () => {console.log(`Server running at port ${port}`)var request = http.request({port: 8080,host: '127.0.0.1',});request.end();request.once('response', (res) => {console.log(res.statusCode);console.log(request.connection);})})setTimeout(()=>{server.close()},2000)
Explanation
-
In line 1, we imported the
HTTPmodule. -
In line 3, we defined the
portnumber of the server. -
In line 5, we used
http.createServer()to create a server and listen to it on port8080. -
In line 6, just for learning purposes, we defined
res.statusCodeto 400, which will be returned when the request is made. -
In line 10, we listed the server using
server.listen(). When the server is running, we request the callback function. -
In line 13, we made a HTTP request using
http.request(). It is aGETrequest by default, with parameters defined in the object. -
In line 18,
request.end()is important, as it finishes the request. If we don’t useend(), the request will be made, but the server will wait for the incoming data untilend()is called. -
In line 20, we listened to the response event on the request we made. In this event, we will print the
connectiondetails using therequest.connectionproperty, and it will return all the details of the connection. -
In line 26, we used
setTimeout()because the Educative feature of a running server will not stop until we stop it by callingserver.close(). It will still give you the desired result, but with anexecution timeout error. You don’t need to write this on your machine.
Output
When we listen to the response event and print the connection details, we get the connection details on the console, and it is a JSON object with lots of connection detail.