无法使用cheerio读取未定义的(读取"状态代码")Nodejs的属性



我正试图获得这个有趣请求的网页标题,很高兴遇到这个问题无法读取未定义的属性(读取"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} nn`);
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:1naveenProjectFinalscrap exampletest.js:29:56)
at self.callback (C:1naveenProjectFinalscrap examplenode_modulesrequestrequest.js:185:22)
at Request.emit (node:events:390:28)
at Request.onRequestError (C:1naveenProjectFinalscrap examplenode_modulesrequestrequest.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)

提前非常感谢

有时,当您在服务器上循环处理多个请求时,套接字可能会挂断(忙于处理其他请求(,或者服务器无法对请求进行排队,这可能导致请求没有响应。最好的解决方案是,在访问请求的属性之前,您必须首先检查响应对象

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}`);
}

相关内容

最新更新