Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property 'statusCode' of undefined

I have done

npm install request

and my code is

const request = require('request');
request('http://www.google.com', function (error, response, body) {
    console.log(response.statusCode);
});

but every time it is throwing a run time error

like image 401
richard937 Avatar asked Oct 16 '25 16:10

richard937


1 Answers

The response object might be undefined if no response was received so you have to check that it exists before accessing statusCode.

See the example here:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

You might not have a response in case there is an error, so make sure to handle the error before trying to handle the response.

like image 72
Mickael B. Avatar answered Oct 18 '25 07:10

Mickael B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!