我試圖為這個有趣的請求獲取網頁的標題,cheerio 面臨這個問題 無法讀取未定義的屬性(讀取'statusCode')但是當我運行嘗試使用靜態值單獨運行時它可以作業
任何人都可以幫助確定我在代碼中所做的錯誤嗎?
這是我的代碼
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)
非常感謝您提前
uj5u.com熱心網友回復:
有時,當您在服務器上回圈執行多個請求時,套接字可能會掛起(忙于其他請求)或服務器無法將請求排隊,這可能導致請求沒有回應。對此的最佳解決方案是,您必須先從請求中檢查回應物件,然后再訪問其屬性。
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}`);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/419455.html
標籤:
