What is the node request event response?

Response event

In this shot, we will learn how to listen to the response event of the request. Response event is emitted when the server sends a response to the request; it is fired only once.

Syntax

request.once('response', (res)=> {})

We know that to listen to an event, we use on or once. Here, we are using once as the response event is fired only once when the server sends a response. When we get response from the server, the response event is emitted. We use the response in the callback function and check the response result.

Code

const http = require('http')
const port = 8080
const server = http.createServer((req,res)=>{
res.statusCode = 400;
res.end();
});
const listener= server.listen(port, () => {
console.log(`Server running at port ${port}`)
var option = {
port: 8080,
host: '127.0.0.1',
};
var request = http.request({
port: 8080,
host: '127.0.0.1',
});
request.end();
request.once('response', (res) => {
console.log(res.statusCode);
})
})
setTimeout(()=>{
server.close()
},5000)

Explanation

  • In line 1, we import the HTTP module.

  • In line 3, we define the port number of the server.

  • In line 5, we use http.createServer() to create a server and listen to it on port 8080.

  • In line 6, just for learning purposes, we have defined res.statusCode to 400, which will be returned when the request is made.

  • In line 10, we list to the server using server.listen(). When the server is running we make the request in the callback function.

  • In line 18, we make a http request using http.request(). It is a get request by default with parameters defined in options.

  • In line 23, request.end() is important as it finishes the request. If we don’t use end(), the request will be made but the server will wait for the incoming data until end() is called.

  • In line 25, we listen to the response event on the request we made, where res is the response from the server. We will print the res.statusCode and it should be 400 as we have defined in the server.

  • In lines 30-32, we use setTimeout() because the educative feature of a running server will not stop until we stop it by calling server.close(). It will still give you the desired result but with execution timeout error. You don’t need to write this on your personal machine.

Output

The statusCode we define in the server when a request is made is the same as the response we are listening to by using request.on('response'). The console prints 400 which is the response we set for the request.

Free Resources