注册
登录
 文档中心 产品介绍 开发指南 API接口 代码样例 使用帮助
Node.js使用request-promise调用Socks5代理IP的代码样例
站大爷 官方 2024-01-21 1411 浏览

温馨提示:

1.  http/https网页均可适用

2.  安装request-promise: npm install request-promise 

3.  安装socks-proxy-agent:npm install socks-proxy-agent


终端IP授权

// 引入第三方 `socks-proxy-agent` 模块
const SocksProxyAgent = require('socks-proxy-agent');
// 引入第三方 `request-promise`
const rp = require('request-promise');

// 代理服务器ip和端口
const proxy_ip = '159.138.141.125';
const proxy_port = 11918;

// 设置代理
let proxy = `socks5h://${proxy_ip}:${proxy_port}`
let agent = new SocksProxyAgent(proxy);

// 要访问的目标网页
let url = 'http://example.com';

let options = {
	uri: url,
	agent: agent,
	resolveWithFullResponse: true,
	gzip: true,  //使用gzip压缩让数据传输更快
	headers: {
		'User-Agent': 'Request-Promise',
	}
};

rp(options).then((res)=> {
	// 输出状态码
	console.log(res.statusCode);
	// 输出返回内容 (已自动进行gzip解压缩)
	console.log(res.body)
}).catch((err) => {
	// 错误处理
	console.log("error")
});

用户名密码授权

// 引入第三方 `socks-proxy-agent` 模块
const SocksProxyAgent = require('socks-proxy-agent');
// 引入第三方 `request-promise`
const rp = require('request-promise');

// 用户名密码授权
const username = 'username';
const password = 'password';

// 代理服务器ip和端口
const proxy_ip = '159.138.141.125';
const proxy_port = 11918;

// 设置代理
let proxy = `socks5h://${username}:${password}@${proxy_ip}:${proxy_port}`
let agent = new SocksProxyAgent(proxy);

// 要访问的目标网页
let url = 'http://example.com';

let options = {
	uri: url,
	agent: agent,
	resolveWithFullResponse: true,
	gzip: true, //使用gzip压缩让数据传输更快
	headers: {
		'User-Agent': 'Request-Promise'
	}
};

rp(options).then((res)=> {
	// 输出状态码
	console.log(res.statusCode);
	// 输出返回内容 (已自动进行gzip解压缩)
	console.log(res.body)

}).catch((err) => {
	console.log("error")
});


立即注册站大爷用户,免费试用全部产品
立即注册站大爷用户,免费试用全部产品