node.js - 特定 app.get 上的快速超时

标签 node.js express

我有一个使用express的nodejs应用程序。

对于特定的GET请求,我想设置一个超时,如果达到这个超时,那么我想彻底结束请求并重定向到超时页面。

我在我的route.js 文件中尝试了以下操作:

 app.get('/exec', isLoggedIn, function(req, res) {

   var customTimeout  = 10000;

   req.connection.setTimeout(customTimeout, function(){
    console.log("TIMED!");
    res.render('timeout.ejs', {
        user: req.user,
    });
   });

   //execution of the GET request
   res.render('success.ejs', {
        user: req.user,
   });

 });

10 秒后,我可以看到“TIMED!”日志中的消息,但我没有重定向到超时页面,并且请求仍在后台运行...

有人可以帮我解决这个问题吗?

最佳答案

这对我有用:

app.get('/exec', isLoggedIn, function(req, res) {
  var customTimeout = 10000;

  res.setTimeout(customTimeout, function(){
    console.log("TIMED!");
    res.render('timeout.ejs', { user: req.user });
  });

  res.render('success.ejs', { user: req.user });
});

我假设您正在执行某种可能需要很长时间才能完成的操作(而不是最后一个 res.render())(10 秒后您想要通知用户操作超时)。

如果该操作无法以某种方式取消,最终它完成并尝试发回响应,在这种情况下,您可能会遇到错误(很可能“Can't发送后设置 header ")。

因此,在发送响应之前,您需要检查超时处理程序是否尚未发送响应。您可以使用res.headersSent为此。

关于node.js - 特定 app.get 上的快速超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31100419/

相关文章:

node.js - "node-debug index.js"和 "run node-inspector, then node --debug index.js"有什么区别

javascript - 类型错误 : Object #<ServerResponse> has no method 'send'

javascript - Node js : Express js asynchronous db query execution-return results got undefiend

node.js - 在检查了各种解决方案后,如何修复 'TypeError: Network Request Failed'错误?

node.js - 如何在 Windows 中捕获 Electron 应用程序的标准输出流?

node.js - 基于 Electron 的应用程序的许可证生成

javascript - 打破 Node.js/Express.Js 中的无限循环

javascript - Prism V2 访问 postgres 数据库被拒绝

javascript - 为什么 Node 中的 PassportJS 不会在注销时删除 session

node.js - Swagger UI Express 插件问题与生产模式下的 webpack 捆绑