user8575224
user8575224

Reputation:

node js request proxy

I send a request through a proxy and always receive such a response

tunneling socket could not be established, cause=read ECONNRESET

or

tunneling socket could not be established, cause= socket hang up

My code

      let settings = {
    url: `url`,
    headers: {
      'Connection': 'keep-alive',
      'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"
    },
    method: 'POST',
    proxy: `http://${ip}:${port}`,
    strictSSL: false
  }
request.request(settings, (err, response, body) => {
 // err here
})

what am I doing wrong ?

Now this error : Error: Tunnel creation failed. Socket error: Error: read ECONNRESET

My code:

  const request = require('request'),
  proxyingAgent = require('proxying-agent');

;

let settings = {
    url: url,
    headers: {
      'Connection': 'keep-alive',
      'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"
    },
    method: 'POST',
    // proxy: `http://${obj.proxy[obj.proxyIdx]}`,
    agent: proxyingAgent.create(`http://${obj.proxy[obj.proxyIdx]}`, url),
  }

Upvotes: 2

Views: 7588

Answers (1)

Grynets
Grynets

Reputation: 2525

About your code, problem possibly lies in your settings object.
You need to use syntax like this:

let settings = {
  url,
  headers: {
  'Connection': 'keep-alive',
  'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"
  },
  method: 'POST',
  proxy: `http://${ip}:${port}`,
  strictSSL: false
}

Here we use ES6 to make object short.

But also, you can establish proxy connection with npm package proxying agent.
Your code should look something like this:

const proxyingAgent = require('proxying-agent');
const fetch = require('node-fetch');

const host = <your host>;
const port = <port>;

const creds = {
  login: 'username',
  password: 'pass'
};

const port = <proxy port>;

const buildProxy = (url) => {
  return {
      agent: proxyingAgent.create(`http://${creds.login}:${creds.password}@${host}:${port}`, url)
  };
};

//If you don't have credentials for proxy, you can rewrite function

const buildProxyWithoutCreds = (url) => {
  return {
      agent: proxyingAgent.create(`http://${host}:${port}`, url)
  };
};

And than you can use it with your url and credentials. We'll use fetch package.

const proxyGetData = async (url, type) => {
   try {
       const proxyData = buildProxyWithoutCreds(url);
       // Make request with proxy. Here we use promise based library node-fetch
       let req = await fetch(url, proxyData);

       if (req.status === 200) {
         return await req[type]();
       }
       return false;
    } catch (e) {
      throw new Error(`Error during request: ${e.message}`);
    }
  };

Upvotes: 3

Related Questions