代码之家  ›  专栏  ›  技术社区  ›  George Katsanos

nodejs https请求返回套接字挂断

  •  0
  • George Katsanos  · 技术社区  · 8 年前
    const https = require("https");
    const fs = require("fs");
    
    const options = {
      hostname: "en.wikipedia.org",
      port: 443,
      path: "/wiki/George_Washington",
      method: "GET",
      // ciphers: 'DES-CBC3-SHA'
    };
    
    const req = https.request(options, (res) => {
      let responseBody = "";
      console.log("Response started");
      console.log(`Server Status: ${res.statusCode} `);
      console.log(res.headers);
      res.setEncoding("UTF-8");
    
      res.once("data", (chunk) => {
        console.log(chunk);
      });
    
      res.on("data", (chunk) => {
        console.log(`--chunk-- ${chunk.length}`);
        responseBody += chunk;
      });
    
      res.on("end", () => {
        fs.writeFile("gw.html", responseBody, (err) => {
          if (err) throw err;
          console.log("Downloaded file");
        });
      });
    });
    
    req.on("error", (err) => {
      console.log("Request problem", err);
    });
    

    回报

    // Request problem { Error: socket hang up
    //     at createHangUpError (_http_client.js:330:15)
    //     at TLSSocket.socketOnEnd (_http_client.js:423:23)
    //     at TLSSocket.emit (events.js:165:20)
    //     at endReadableNT (_stream_readable.js:1101:12)
    //     at process._tickCallback (internal/process/next_tick.js:152:19) code: 'ECONNRESET' }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Jonas Wilms    8 年前

    http.request() 打开到服务器的新隧道。它返回一个可写流,允许您将数据发送到服务器,并使用服务器响应的流调用回调。现在你遇到的错误( ECONNRESET )基本上意味着隧道已经关闭了。这种情况通常发生在低级别(非常不可能)发生错误或由于未接收到数据而导致隧道超时时。在您的情况下,服务器只在您向其发送内容时才响应,即使它是空包,因此您所要做的就是结束流,使其作为空包刷新到服务器,从而使其响应:

     req.end();
    

    你可能想看看 request 使您能够避免处理此类低级事务的包。