通过NodeJS中的SOCKS5代理执行http请求

Fre*_*efl 27 proxy http tor node.js

我打算通过Tor在NodeJS中做一系列的HTTP请求.
Tor使用SOCKS5,所以我出去搜索了一种在NodeJS中代理HTTP请求的方法.
我打算使用默认的http.request()函数来完成工作.
但是,我似乎无法找到使用代理的方法.
有人建议我可以这样做:

var http = require("http");
var options = {
  host: "localhost",
  port: 9050,
  path: "http://check.torproject.org",
  method: 'GET',
  headers: {
    Host: "http://check.torproject.org",
  }
};
var req = http.request(options, function(res) {
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});
Run Code Online (Sandbox Code Playgroud)

但它没有用.
那么,有什么建议吗?

Mat*_*hew 29

我刚刚发布了两个可以帮助你做到这一点的模块:socks5- http -clientsocks5- https -client.

只需使用它们而不是默认http模块.API是一样的.例如:

require('socks5-http-client').request(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 这会给出“错误:由于某些原因连接ECONNREFUSED 127.0.0.1:1080”,它会用1080覆盖我的端口9050 (2认同)

Poi*_*rks 9

我知道我正在回答一个老问题但是有一个更好的解决方案可用于这个问题,关于如何在Node.js中使用sock4和sock5代理.为简单起见,我将使用请求承诺模块,但您也可以使用裸请求模块.

需求:socks-proxy-agent,请求承诺

例:

async function main() {


var proxy = "socks4://1.2.3.4:35618"

var agent = new SocksProxyAgent(proxy);

var options = {
    uri: 'http://targetUrl',
    agent: agent,
    headers: {
        'User-Agent': 'Request-Promise'
    }
}

try {
    var responce = await rp(options)
} catch(err) {
    console.log(err)
}

console.log(responce)  }
Run Code Online (Sandbox Code Playgroud)

  • 您可以尝试替换此 URL https://wtfismyip.com/json 代替目标 URL。如果代理工作正常,您应该看到代理的 IP 和代理的 ISP 作为您自己的 IP。我希望你明白这一点 (2认同)