如何解决Cheerio.js:$find承诺被拒绝
我试图使用Cheerio从特定的父元素中获取某个HTML类的子元素。这是我的代码:
const $ = cheerio.load(validHtmlBody);
var sections = $(".zloOqf").find(".fl").length;
return res.status(400).send(sections);
但是,此代码被拒绝,并出现UnhandledPromiseRejectionWarning
错误:
(node:60502) UnhandledPromiseRejectionWarning: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 1
at ServerResponse.writeHead (_http_server.js:208:11)
at ServerResponse.writeHead (index.js:44:26)
at ServerResponse._implicitHeader (_http_server.js:199:8)
at ServerResponse.end (_http_outgoing.js:717:10)
at ServerResponse.send (/node_modules/express/lib/response.js:221:10)
at index.js:41:30
at processTicksAndRejections (internal/process/next_tick.js:81:5)
(node:60502) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:60502) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
将此代码放入try catch块中并返回错误只会返回一个空的json。
解决方法
问题是您将number
传递到.send()
。这将尝试覆盖状态400,并且由于它不是有效的http状态,因此将抛出所显示的错误。
如果您打算将数字(即节数)发送回客户端,则可以将其作为字符串发送(express会自动将响应内容类型更改为“ text / html”:
return res.status(400).send(sections.toString());
另一种可能性是返回一个指示段数的json:
return res.status(400).json({numberOfSections: sections});
注意:http-status 400可能不是此处的正确代码,因为这表明客户端请求不正确...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。