How to use the on function from request

Find comprehensive JavaScript request.on code examples handpicked from public code repositorys.

request.on is a method in the request module of Node.js that allows attaching event handlers to track different stages of an HTTP request-response cycle.

633
634
635
636
637
638
639
640
641
642
      .catch();
    //console.log(apidata.item.item_id);
    //res.send(apidata);
  });
});
request.on('error', error => {
  console.log(error);
});
request.write(JSON.stringify(itemData));
request.end();
fork icon0
star icon0
watch icon1

321
322
323
324
325
326
327
328
329
330
if (data) {
    request.write(data);
}

// Treat response.
request.on('response', (response) => {
    // Read the result.
    let result = '';
    response.on('data', (chunk) => {
        result += chunk;
fork icon0
star icon0
watch icon1

+ 3 other calls in file

How does request.on work?

The request.on() function in the request module in Node.js allows you to listen for different events in a HTTP request or response, such as the data event when data is received, the end event when the request is complete, or the error event when an error occurs.

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const request = require("request");

// Make a request to an API endpoint
const apiEndpoint = "https://jsonplaceholder.typicode.com/todos/1";
const req = request(apiEndpoint);

// Handle different events during the request lifecycle
req.on("response", function (response) {
  console.log("Response status code:", response.statusCode);
});

req.on("data", function (chunk) {
  console.log("Received data:", chunk);
});

req.on("error", function (error) {
  console.error("Error:", error);
});

req.on("end", function () {
  console.log("Request completed.");
});

In this example, we're making a request to an API endpoint using the request library. We're attaching listeners to the request object to handle different events during the request lifecycle: response: This event is emitted when the server responds to the request. We're logging the response status code to the console. data: This event is emitted when the server sends a chunk of data in the response body. We're logging the received data to the console. error: This event is emitted if there's an error during the request. We're logging the error to the console. end: This event is emitted when the request has been completed. We're logging a message to the console to indicate that the request is finished.