简体   繁体   English

如何从setTimeout回调发送http响应 - 表达

[英]How to send http response from setTimeout callback - express

I would like to have custome response time-out, so that I am trying to send the response from setTimeout callback if the processing time exceeds certain interval. 我想有客户响应超时,所以如果处理时间超过一定的间隔,我试图从setTimeout回调发送响应。

In the following example, I set 20ms as time-out period within which services.getReport() has to be processed otherwise the API has to send response as response_timed_out . 在下面的示例中,我将20ms设置为必须处理services.getReport()的超时时间,否则API必须将响应作为response_timed_out发送。

The following code works fine but it throws exception like 以下代码工作正常,但它抛出异常,如

Cannot set headers after they are sent to the client 发送到客户端后无法设置标头

router.post("/getReport", (req, res) => {
  setTimeout(() => {
    res.send({ status:503, msg: "response_timed_out" });
  }, 20);
  services.getReport(req, res);
});

You can use setTimeout method on the request object to define timeout time for each route. 您可以在请求对象上使用setTimeout方法来定义每个路由的超时时间。

router.post("/getReport", (req, res) => {
  req.setTimeout(2000);
  services.getReport(req, res);
});

You can also define timeout time globally for all routes on the server. 您还可以为服务器上的所有路由全局定义超时时间。

const server = app.listen(port, () => {});
server.setTimeout(15000);

You can also provide the second argument which is callback that will run when timeout occurs. 您还可以提供第二个参数,即在发生超时时将运行的回调。 If you want the callback then you call setTimeout on the response. 如果您想要回调,那么您可以在响应上调用setTimeout

router.post("/getReport", (req, res) => {
  res.setTimeout(2000, () => res.send('timed_out'));
  services.getReport(req, res);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM