admin管理员组文章数量:1336631
I have done
npm install request
and my code is
const request = require('request');
request('', function (error, response, body) {
console.log(response.statusCode);
});
but every time it is throwing a run time error
I have done
npm install request
and my code is
const request = require('request');
request('http://www.google.', function (error, response, body) {
console.log(response.statusCode);
});
but every time it is throwing a run time error
Share asked Jan 23, 2020 at 10:14 richard937richard937 1992 gold badges3 silver badges11 bronze badges 3- your code looks ok no issue with the code, I have tried and it's printing the correct statusCode – Sohail Ashraf Commented Jan 23, 2020 at 10:21
- Ok, are you using a mobile network ?? – richard937 Commented Jan 24, 2020 at 11:29
- In my case this happened due to a very dumb mistake on my part - I copied my Postman tests from another request and pasted it in Pre-req. tab instead of under the Tests tab! – Mirza Sisic Commented Jul 6, 2021 at 10:00
2 Answers
Reset to default 4The 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.', 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. Because the undefined
means there is no response
object:
const request = require('request');
request('http://www.google.', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
});
本文标签: javascriptTypeError Cannot read property 39statusCode39 of undefinedStack Overflow
版权声明:本文标题:javascript - TypeError: Cannot read property 'statusCode' of undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742260563a2442431.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论