我正在尝试使用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。
发布于 2020-08-16 12:33:03
问题是您向.send()
传递了一个number
。这将尝试覆盖状态400,由于它不是有效的http-status,因此将抛出所显示的错误。
如果您的意图是向客户端发送一个数字,即区段数,您可以将其作为字符串发送(express会自动将响应内容类型更改为"text/html":
return res.status(400).send(sections.toString());
另一种可能是返回一个json,表示节的数量:
return res.status(400).json({numberOfSections: sections});
注意: http-status 400可能不是正确的代码,因为这将表明客户端请求是不正确的……
https://stackoverflow.com/questions/63435734
复制相似问题