richard937
richard937

Reputation: 199

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

Upvotes: 4

Views: 19157

Answers (2)

Mickael B.
Mickael B.

Reputation: 5215

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.

Upvotes: 4

Burak Ayyildiz
Burak Ayyildiz

Reputation: 465

it looks like that there is no response. I suggest you to log the error object as well and analyse the error message. Adjust also your code by checking if the response object is defined. Because the undefined means there is no response object:

const 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);  
  console.log('body:', body); 
});

Upvotes: -1

Related Questions