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 = 8080const 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
HTTPmodule. -
In line 3, we define the
portnumber of the server. -
In line 5, we use
http.createServer()to create a server and listen to it on port8080. -
In line 6, just for learning purposes, we have defined
res.statusCodeto 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
httprequest usinghttp.request(). It is agetrequest by default with parameters defined in options. -
In line 23,
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 25, we listen to the
responseevent on the request we made, whereresis the response from the server. We will print theres.statusCodeand it should be400as we have defined in the server. -
In lines 30-32, we use
setTimeout()because theeducativefeature of a running server will not stop until we stop it by callingserver.close(). It will still give you the desired result but withexecution timeouterror. 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.