【问题标题】:Do POST requests expire after no response from server?POST 请求是否在服务器没有响应后过期?
【发布时间】:2020-06-12 15:33:38
【问题描述】:

当使用setTimeout() 向我们的API 发出POST 请求时,我正在我的服务器上设置一个计时器。在计时器执行并发送200 OK 响应后,我想对我的应用程序中的一些 DOM 元素进行更新。我的问题是,如果将计时器设置为长时间(例如 30 分钟以上),POST 请求会过期并发送400 响应,还是会无限期地等待直到做出响应?我的猜测是它会过期,但我不是 100% 确定。如果是这样,如何确保在计时器执行后客户端会收到响应?

这是将在 POST 请求中执行的代码:

setTimeout(() => {
   io.emit('insertWaitTime',{AlertID: req.body.AlertID, Time: null});
   io.emit('updateStep',{AlertID: req.body.AlertID, Step: req.body.NextStep}, (res) => {
      if(!boolean){
       console.log("ERROR: /api/setTimer: Could not update alert");
      }else{
       res.status(200).send({
         Message: "SUCCESS: timer was executed",
         Status: 200
       })
      }
  })
}, (60000 * req.body.Minutes));

在 200 响应之后,我将更新我的 DOM 元素客户端:

let timerObj = {
 Minutes: 15
 AlertID: this.props.AlertID,
 NextStep: this.props.NextStep,
}

axios.post('/setTimer', timerObj, (res) => {
  // do all dom updating after good response

  console.log(res);

  if(res.Status === 200){
   document.getElementByID('myel').style.display = 'none';
  }

})

我需要将此计时器设置为服务器端,因为这可能会被多次调用,并且不适合设置客户端,因为它可能会导致严重的副作用。如果有人对这是否可行有任何想法,或者我必须走一条完全不同的路线,我将不胜感激。谢谢!

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    在 Node.js v13.0.0 之后,默认超时时间从 120s 更改为 0(无超时)

    您可以使用 Axios 模块在客户端设置超时,如下所示:

    axios({
      method: "post",
      url: 'http://example.com/api',
      timeout: 1000 * 5, 
    })
      .then(response => {
      })
      .catch(error => {
        console.log(error);
    });
    

    或者设置服务器超时

    const http = require('http');
    const server = http.createServer(function (req, res) {
      res.write('Test');
      res.end();
    });
    server.listen(8080);
    server.timeout = 2000;
    

    【讨论】:

    • 哇,我从没想过在 axios 请求中设置超时。这可能比在 POST 请求中调用 setTimeout() 更好。
    • 如果用户刷新页面,这会导致问题吗?
    • 如果页面重新加载,请参考这里stackoverflow.com/questions/41449700/…
    • 好的,所以如果页面被刷新,似乎无法从该 ajax 请求中获取响应。请求将立即发送,并将从服务器端执行,这很好,但是当我需要从该请求中获取响应时,它会变得很棘手。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 2020-08-19
    • 2015-10-28
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多