nodejs 使用https请求并配置https-proxy-agent代理
在使用https请求时,可以使用https模块提供的request方法,同时配置https-proxy-agent代理。
示例代码:
const https = require('https');
const HttpsProxyAgent = require('https-proxy-agent');
// 配置代理
const proxy = 'http://proxy.example.com:8080';
const agent = new HttpsProxyAgent(proxy);
// 发送https请求
const options = {
hostname: 'www.example.com',
path: '/',
method: 'GET',
agent: agent // 设置代理
};
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (error) => {
console.error(error);
});
req.end();
其中,HttpProxyAgent是一个用于https代理的代理类,可以通过传入代理地址和端口创建一个实例,然后将其设置在request的options中的agent属性中即可。
原文地址: https://www.cveoy.top/t/topic/bIrh 著作权归作者所有。请勿转载和采集!