【问题标题】:response timeout on http requesthttp请求的响应超时
【发布时间】:2017-07-25 07:35:16
【问题描述】:

我正在使用 electron.js 制作一个应用程序,并且我已经到了需要发出 http 请求来调用 php 的地步。一开始的响应时间很短,应用程序在接收数据之前就失败了。然后我在 HTTP 路径上设置了一个 timeOut,这样服务器响应的等待时间就会增加。类似的问题是好像没有超时,不等待指示的。

你知道解决这个问题的方法吗?

var http = require('http');
    var options = {
      timeout: 50000,
      host: localStorage.getItem('server'),
      port: localStorage.getItem('port'),
      path: localStorage.getItem('directori') + '?nosession=1&call=ciberFiSessio&numSerie='+ localStorage.getItem("pc")
    };
http.get(options, function(res) {
      alert("hola");
      if (res.statusCode  == 200){
        //reinicia();

        res.on('data', function (chunk) {
          str = chunk;
          alert(str);

          var myJSON = JSON.parse(str);
          //alert(myJSON.fi);

          if(parseInt(myJSON.fi)==0){
            alert("Hi ha hagut un problema!");
          }else{
            reinicia();
          }

        });

      }else{
        alert("El lloc ha caigut!");
        alert(res.statusCode);
      }
    }).on('error', function(e) {
      alert("Hi ha un error: " + e.message);
    });

【问题讨论】:

    标签: node.js httprequest electron httpresponse


    【解决方案1】:

    使用 node-fetch 库,它支持更复杂的选项,并且还与 Promises 一起使用,这是设计异步应用程序的现代方法。 https://www.npmjs.com/package/node-fetch

    支持的选项(来自文档,包括timeout

    {
        method: 'GET'
        , headers: {}        // request header. format {a:'1'} or {b:['1','2','3']}
        , redirect: 'follow' // set to `manual` to extract redirect headers, `error` to reject redirect
        , follow: 20         // maximum redirect count. 0 to not follow redirect
        , timeout: 0         // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies)
        , compress: true     // support gzip/deflate content encoding. false to disable
        , size: 0            // maximum response body size in bytes. 0 to disable
        , body: empty        // request body. can be a string, buffer, readable stream
        , agent: null        // http.Agent instance, allows custom proxy, certificate etc.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      相关资源
      最近更新 更多