[英]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但每次它抛出一个运行时错误
The response
object might be undefined
if no response was received so you have to check that it exists before accessing statusCode
.如果未收到响应,则
response
对象可能undefined
,因此您必须在访问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.如果出现错误,您可能没有响应,因此请确保在尝试处理响应之前处理错误。
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.通过检查是否定义了
response
对象来调整您的代码。 Because the undefined
means there is no response
object:因为
undefined
意味着没有response
对象:
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.