简体   繁体   English

Node Js 多个 HTTPS 请求连接在一个脚本中

[英]Node Js multiple HTTPS request connection in one script

Hey guys I'm kinda stuck in my first attempt to do multiple https connections with nodejs.嘿伙计们,我第一次尝试使用 nodejs 进行多个 https 连接时有点卡住了。 The following code won't start and I get an error message which says:以下代码将无法启动,我收到一条错误消息,内容为:

Hint: hit control+c anytime to enter REPL.
events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: socket hang up
    at createHangUpError (_http_client.js:323:15)
    at TLSSocket.socketOnEnd (_http_client.js:426:23)
    at TLSSocket.emit (events.js:203:15)
    at TLSSocket.EventEmitter.emit (domain.js:448:20)
    at endReadableNT (_stream_readable.js:1143:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
    at TLSSocket.socketOnEnd (_http_client.js:426:9)
    at TLSSocket.emit (events.js:203:15)
    [... lines matching original stack trace ...]
    at process._tickCallback (internal/process/next_tick.js:63:19)

(To exit, press ^C again or type .exit)

Here is my code:这是我的代码:

const https = require('https');

function RandomIp(length) {
   var result           = '';
   var characters       = '123456789';
   var charactersLength = characters.length;

   for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }

   return result;
}

var userAgent = 'iPhone / Safari 12.1.1 [Mobile]: Mozilla/5.0 (iPhone; CPU OS 10_15_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Mobile/14E304 Safari/605.1.15';
var flag      = false;
var ip        = RandomIp(3) +"."+ RandomIp(3) +"."+ RandomIp(3) +"."+ RandomIp(3);

const options = {
  hostname: 'sh0rt.me',
  port: 443,
  path: '/r/XX6fYM',
  method: 'GET',
  headers: {
     'X-Forwarded-For': ip,
     'User-Agent': userAgent
  }
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
    console.log("first connection successfull!")
    console.log(flag);

    flag=!flag;
    console.log(flag);

    if (flag == true){
      console.log("Ready for second connection");

      const optionsd = {
        hostname: 'sh0rt.me',
        port: 443,
        path: '/r/XX6fYM',
        method: 'GET',
        headers: {
          'X-Forwarded-For': ip,
          'User-Agent': userAgent,
          'Cookies' : 'cookies lol'
        }
      };

      const reqd = https.request(optionsd, (resd) => {
        console.log('statusCode:', resd.statusCode);
        console.log('headers:', resd.headers);

        resd.on('data', (d) => {
          //process.stdout.write(d);
          console.log("1. Anfrage erfolgreich!")
          console.log(flag);
          console.log(options);
        })
      });

    };

    req.on('error', (e) => {
      console.error(e);
    });
  });
});

I know this question is very long but I will be glad if anyone can tell me what I did wrong.我知道这个问题很长,但如果有人能告诉我我做错了什么,我会很高兴。

Thanks guys ^^谢谢各位^^

There's a lot of issues on that code that can be addressed, for starters, you are not adding a listener for the 'error' event in the 'reqd' object (returned by your second https.request), that's why is not printing the error in the console.该代码有很多问题可以解决,对于初学者来说,您没有在“reqd”对象(由您的第二个 https.request 返回)中为“error”事件添加侦听器,这就是为什么不打印控制台中的错误。

You don't really need to add a req.end() call in this code because the connection will be finished when the script ends (in this context is fine), but also, don't use the included https module to do request, are far better implementations of this that don't need event binding, for example:您实际上不需要在此代码中添加 req.end() 调用,因为连接将在脚本结束时完成(在此上下文中很好),而且,不要使用包含的 https 模块进行请求, 是不需要事件绑定的更好的实现,例如:

  • isomorphic-fetch (a very similar implementation of the fetch function you can find in browsers) isomorphic-fetch (您可以在浏览器中找到的 fetch 函数的一个非常相似的实现)
  • axios (very nice and complete) axios (非常好且完整)

Other thing, never do:其他事情,永远不要做:

if(flag == true)

because if expect a true or false value, so flag is already that, is as simple as:因为如果期望一个真值或假值,那么标志就已经是这样了,就像:

if(flag)

Also, for what i see (correct me if I'm wrong) you are generating random ips?, that probably will not work, because ips are not random and they have a structure, is not like using four 3 digit numbers and it will be a valid ip address.另外,对于我所看到的(如果我错了,请纠正我)您正在生成随机 ips?,这可能不起作用,因为 ips 不是随机的,它们有一个结构,不像使用四个 3 位数字,它会是一个有效的IP地址。

Try using ips you already know first, probably is throwing error because of that.首先尝试使用您已经知道的 ips,可能因此而引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM