首页 > 解决方案 > 在 NodeJS 中使用 Request 或 Needle 的套接字挂断错误

问题描述

尝试连接到外部网站时出现 Socket Hangup 错误,下面给出了一个失败站点的示例。该代码适用于其他站点,如果我用 Python 重写代码,我可以成功访问测试站点。我无法对外部站点进行更改,因此我希望增强 NodeJS 脚本来处理连接。任何帮助表示赞赏

let request = require("request-promise");
let needle = require("needle");

//Check if can connect to site

    let arrTestCases = ["https://compassandstars.com"];

    for (x in arrTestCases) {
         chkcon(arrTestCases[x])
    }

    async function chkcon(req) {
        let resultJSON = {};
        let data;
        try {
            console.log ("Validating blog " + req);
    //Attempt using RequestPromise, fails with same error
    //      let getURL = await request({
    //          url: req,
    //          headers: {
    //              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' 
    //          }
    ////            headers: {
    ////                'User-Agent': 'ouruseragent',
    ////                'Connection': 'keep-alive'
    ////            }
    //      })

            needle('get', req)

             .then(function(response) {
                resultJSON = {ValidURL: true};
                console.log("URL Validated successfully", response.body);
             })
             .catch(function(err) {
                console.log(err);
             })

        } catch (e) {
            console.log("Bad Blog URL ",e.message);
        } finally {
            console.log("Result: " + JSON.stringify(resultJSON), req);

        }

错误响应:

Result: {} https://compassandstars.com
{ Error: socket hang up
    at TLSSocket.onConnectEnd (_tls_wrap.js:1073:19)
    at Object.onceWrapper (events.js:219:13)
    at TLSSocket.emit (events.js:132:15)
    at endReadableNT (_stream_readable.js:1101:12)
    at process._tickCallback (internal/process/next_tick.js:152:19)
  code: 'ECONNRESET',
  path: null,
  host: 'compassandstars.com',
  port: 443,
  localAddress: undefined }

我可以在 AWS Lambda 上使用 NodeJS 8.10 重新创建该问题,并在我的机器上使用 NodeJS 9.6.1 在本地重新创建该问题。

我的研究表明,找到兼容的密码来建立 SSL 连接可能是错误的,但我无法找出如何强制 Request 更改请求以处理此问题。

标签: javascriptnode.jsrequestneedle.js

解决方案


推荐阅读