1
votes

I am making a post request using request package. how can I set timeout 500 ms while requesting.

var request = require('request');

request({
      url: 'myUrl',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'authToken': 'myToken'
      },
      timeout: 500,
      json: infoObj
    })
      .on('response', function(response) {
        console.log('request response=============',response.statusCode)

      })
      .on('error', function(err) {
          console.log('error===',err);
      });

when tried using timeout: 500, above example got error

{ Error: ETIMEDOUT at Timeout._onTimeout (F:\gomean\globeone\node_modules\request\request.js:796:17) at tryOnTimeout (timers.js:224:11) at Timer.listOnTimeout (timers.js:198:5) code: 'ETIMEDOUT', connect: true }

2
Can you tell us what are you trying to achieve? - Rajesh
updated question that i tried - Shaishab Roy
Your error looks like what you get when you get an unhandled timeout error. I don't see any error handler in your code that would catch errors, including the timeout error. - jfriend00
node engine version? - Kamal

2 Answers

0
votes

Request Doc: timeout - Integer containing the number of milliseconds to wait for a server to send response headers (and start the response body) before aborting the request.

var request = require('request');

request({
      url: 'myUrl',
      method: 'POST',

      timeout: 500,

      headers: {
        'Content-Type': 'application/json',
        'authToken': 'myToken'
      },
      json: infoObj
    })
      .on('response', function(response) {
        console.log('request response=============',response.statusCode)

      })
0
votes

You need to include a callback to catch the error. From the documentation:

You can detect timeout errors by checking err.code for an 'ETIMEDOUT' value. Further, you can detect whether the timeout was a connection timeout by checking if the err.connect property is set to true.

And an example:

request.get('http://10.255.255.1', {timeout: 1500}, function(err) {
    console.log(err.code === 'ETIMEDOUT');
    // Set to `true` if the timeout was a connection timeout, `false` or
    // `undefined` otherwise.
    console.log(err.connect === true);
    process.exit(0);
});