Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Cheerio.js:$().find()承诺被拒绝

Cheerio.js:$().find()承诺被拒绝
EN

Stack Overflow用户
提问于 2020-08-16 10:26:17
回答 1查看 64关注 0票数 1

我正在尝试使用Cheerio从特定的父元素中获取某个HTML类的子元素。下面是我的代码:

代码语言:javascript
运行
AI代码解释
复制
const $ = cheerio.load(validHtmlBody);
var sections = $(".zloOqf").find(".fl").length;
return res.status(400).send(sections);

但是,此代码会被拒绝,并出现UnhandledPromiseRejectionWarning错误:

代码语言:javascript
运行
AI代码解释
复制
(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。

EN

回答 1

Stack Overflow用户

发布于 2020-08-16 12:33:03

问题是您向.send()传递了一个number。这将尝试覆盖状态400,由于它不是有效的http-status,因此将抛出所显示的错误。

如果您的意图是向客户端发送一个数字,即区段数,您可以将其作为字符串发送(express会自动将响应内容类型更改为"text/html":

代码语言:javascript
运行
AI代码解释
复制
return res.status(400).send(sections.toString());

另一种可能是返回一个json,表示节的数量:

代码语言:javascript
运行
AI代码解释
复制
return res.status(400).json({numberOfSections: sections});

注意: http-status 400可能不是正确的代码,因为这将表明客户端请求是不正确的……

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63435734

复制
相关文章

相似问题

添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档