node js请求代理

时间:2018-01-02 16:41:58

标签: node.js proxy request

我通过代理发送请求并始终收到此类回复

tunneling socket could not be established, cause=read ECONNRESET

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

我的代码

      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
})

我做错了什么?

现在出现此错误:错误:隧道创建失败。套接字错误:错误:读取ECONNRESET

我的代码:

  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),
  }

1 个答案:

答案 0 :(得分:2)

关于您的代码,问题可能在于您的settings对象。
你需要使用这样的语法:

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
}

这里我们使用ES6来缩短对象。

但是,您也可以使用npm package proxying agent建立代理连接 您的代码应如下所示:

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)
  };
};

并且您可以将它与您的网址和凭据一起使用。我们将使用fetch包。

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}`);
    }
  };