简体   繁体   中英

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. 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.

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:

  • isomorphic-fetch (a very similar implementation of the fetch function you can find in browsers)
  • axios (very nice and complete)

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.

Try using ips you already know first, probably is throwing error because of that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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