【问题标题】:Node.js timeout with requestify POST请求 POST 的 Node.js 超时
【发布时间】:2016-11-02 06:41:15
【问题描述】:

我正在尝试使用从 node.js 到 PHP 文件的 POST 请求用户的状态。 我的问题是我调用的网络服务回复速度非常慢(4 秒),所以我认为 .then 在 4 秒之前完成,因此什么也不返回。知道我是否可以延长请求的时间吗?

requestify.post('https://example.com/', {
              email: 'foo@bar.com'
            })
            .then(function(response) {
                var answer = response.getBody();
                console.log("answer:" + answer);
            });

【问题讨论】:

    标签: node.js post requestify


    【解决方案1】:

    我对 requestify 不是很了解,但是您确定可以使用 post 到 https 地址吗?在自述文件中,仅 requestify.request(...) 使用 https 地址作为示例。 (see readme)

    我绝对可以给您的一个提示是始终兑现您的承诺:

    requestify.get(URL).then(function(response) {
        console.log(response.getBody())
    }).catch(function(err){
        console.log('Requestify Error', err);
        next(err);
    });

    这至少应该给你你的承诺的错误,你可以指定你的问题。

    【讨论】:

      【解决方案2】:

      对 Requestify 的每次调用都允许您传递一个 Options 对象,该对象的定义在此处描述:Requestify API Reference

      您正在使用 short 方法进行 POST,所以我将首先展示它,但同样的语法也适用于 put,请注意 get、delete、head 不接受一个数据参数,你通过params配置属性发送url查询参数。

      requestify.post(url, data, config)
      requestify.put(url, data, config)
      requestify.get(url, config)
      requestify.delete(url, config)
      requestify.head(url, config)
      

      现在,config 有一个 timeout 属性

      超时 {number}

      为请求设置超时(以毫秒为单位)。

      因此我们可以使用以下语法指定 60 秒的超时时间:

      var config = {};
      config.timeout = 60000;
      requestify.post(url, data, config)
      

      或内联:

      requestify.post(url, data, { timeout: 60000 })
      

      现在让我们把它放在你的原始请求中:

      正如@Jabalaja 指出的那样,您应该捕获任何异常消息,但是您应该在继续时使用错误参数来执行此操作。 (.then)

      requestify.post('https://example.com/', {
          email: 'foo@bar.com'
      }, {
          timeout: 60000
      })
      .then(function(response) {
          var answer = response.getBody();
          console.log("answer:" + answer);
      }, function(error) {
          var errorMessage = "Post Failed";
          if(error.code && error.body)
              errorMessage += " - " + error.code + ": " + error.body
          console.log(errorMessage);
          // dump the full object to see if you can formulate a better error message.
          console.log(error);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-30
        • 1970-01-01
        • 2017-04-01
        • 2020-05-30
        • 2021-07-23
        • 1970-01-01
        • 1970-01-01
        • 2011-09-07
        相关资源
        最近更新 更多