[英]Cannot read properties of undefined (reading 'statusCode') Nodejs using cheerio
我試圖為這個有趣的請求獲取網頁的標題,cheerio 面臨這個問題無法讀取未定義的屬性(讀取'statusCode')但是當我運行嘗試使用 static 值單獨運行時它可以工作
任何人都可以幫助確定我在代碼中所做的錯誤嗎?
這是我的代碼
var request = require("request");
var cheerio = require("cheerio");
jsonData = [
{ Domain: "bar-n-ranch.com" },
{ Domain: "barcelona-enabled.com" },
{ Domain: "barefootamelia.com" },
{ Domain: "barmranch.com" },
{ Domain: "barnstablepatriot.com" },
{ Domain: "barrieapartmentrentalsonline.com" },
{ Domain: "basquehomes.com" },
{ Domain: "bassmaster.com" },
{ Domain: "basswoodresort.com" },
];
function fetchTitle(url, onComplete = null) {
request(url, function (error, response, body) {
var output = url; // default to URL
if (!error && response.statusCode === 200) {
var $ = cheerio.load(body);
console.log(`URL = ${url}`);
var title = $("head > title").text().trim();
console.log(`Title = ${title}`);
output = `[${title}] (${url})`;
} else {
console.log(`Error = ${error}, code = ${response.statusCode}`);
}
console.log(`output = ${output} \n\n`);
if (onComplete) onComplete(output);
});
}
jsonData.forEach(function (table) {
var tableName = table.Domain;
var URL = "http://" + tableName;
fetchTitle(URL);
});
當傳遞像 fetchtitle("https://www.googlecom") 這樣的值時,它可以工作,但是當我嘗試循環 JSON 數據時出現錯誤
錯誤堆棧跟蹤 ^
TypeError: Cannot read properties of undefined (reading 'statusCode')
at Request._callback (C:\1\naveen\Project\Final\scrap example\test.js:29:56)
at self.callback (C:\1\naveen\Project\Final\scrap example\node_modules\request\request.js:185:22)
at Request.emit (node:events:390:28)
at Request.onRequestError (C:\1\naveen\Project\Final\scrap example\node_modules\request\request.js:877:8)
at ClientRequest.emit (node:events:390:28)
at Socket.socketErrorListener (node:_http_client:447:9)
at Socket.emit (node:events:390:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
非常感謝您提前
有時,當您在服務器上循環執行多個請求時,套接字可能會掛起(忙於其他請求)或服務器無法將請求排隊,這可能導致請求沒有響應。 對此的最佳解決方案是,在訪問其屬性之前,您必須首先檢查來自請求的響應 object。
if (!error && (response && response.statusCode) === 200) {
var $ = cheerio.load(body);
console.log(`URL = ${url}`);
var title = $("head > title").text().trim();
console.log(`Title = ${title}`);
output = `[${title}] (${url})`;
}
else {
console.log(`Error = ${error}, code = ${response && response.statusCode}`);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.