node.js使用代理踩的坑最终的解决方案使用https和socks-proxy-agent解决

安装环境

npm install https

npm install socks-proxy-agent

调用环境

javascript 复制代码
const https = require('https');
const { SocksProxyAgent } = require('socks-proxy-agent');

定义一个公用请求方法

javascript 复制代码
function httpsRequest(options, body) {
    return new Promise((resolve, reject) => {
        const req = https.request(options, (res) => {
            let responseData = '';
            
            res.on('data', (chunk) => {
                responseData += chunk;
            });

            res.on('end', () => {
                resolve(responseData); // 当收到完整的响应数据时,解析 Promise
            });
        });

        req.on('error', (error) => {
            reject(error); // 在请求错误时拒绝 Promise
        });

        if (body) {
            req.write(body); // 写入请求主体
        }
        req.end(); // 结束请求
    });
}

定义一个获取代理的方法

javascript 复制代码
async function fetchAndPrintUrl() {
    const url = '获取json返回的socks5的代理';

    try {
        const response = await axios.get(url);
        return response.data
    } catch (error) {
        console.error('Error fetching the URL:', error);
    }
}

写一个实际掉用方法的方法

javascript 复制代码
async function new_get_token(ak, sk, lujin, url, appid, code) {
    // 示例使用
    let method = 'POST';
    let offset = 0; // 如有需要,替换为实际的偏移量
    let dataObj = {
        appId: appid,
        code: code
    };

    // 使用 JSON.stringify 转换为 JSON 字符串
    let body = JSON.stringify(dataObj);
    let headers = encryption_data2(ak, sk, method, lujin, body, offset, appid);
    try {
        const portData = await fetchAndPrintUrl();
        const pp = portData.data[0];
        let ip = pp.ip;
        let port = pp.port;
        const socksProxyUrl = `socks5://${ip}:${port}`;
        // 忽略 SSL/TLS 证书验证
        const agent = new SocksProxyAgent(socksProxyUrl, {
            rejectUnauthorized: false  // 忽略 SSL/TLS 证书验证
        });
        const options = {
            hostname: ip,
            port: port,
            path: url,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(body),
                ...headers
            },
            agent: agent  // 如果您没有使用代理,可以省略这一行
        };
        let response = await httpsRequest(options, body);
        return response.data; // 返回数据而不是打印
    } catch (error) {
        console.error('Error making request:', error);
        throw error; // 抛出错误
    }
}

CHATGPT协助整理文档

1. 定义一个通用的 HTTPS 请求方法

javascript 复制代码
function httpsRequest(options, body) {
    // ...
}

这段代码定义了一个名为 httpsRequest 的函数,用于发起 HTTPS 请求。它利用 JavaScript 的 Promise 来处理异步操作,确保请求完成后再继续执行后续代码。这个函数接受两个参数:options(请求配置)和 body(请求体)。

  • new Promise((resolve, reject) => { ... }):创建一个新的 Promise 对象,用于处理异步操作。
  • https.request(options, (res) => { ... }):发起 HTTPS 请求,其中 options 包含了请求的配置信息(如 URL、请求方法、头部等)。
  • res.on('data', (chunk) => { ... }):当接收到数据块时触发,将数据块累加到 responseData 字符串中。
  • res.on('end', () => { ... }):当响应结束时触发,此时 resolve(responseData) 会解析 Promise,并返回完整的响应数据。
  • req.on('error', (error) => { ... }):监听请求过程中的错误,如有错误则通过 reject(error) 拒绝 Promise。
  • if (body) { req.write(body); }:如果有请求体,则将其写入请求中。
  • req.end();:结束请求。

2. 定义一个获取代理的方法

javascript 复制代码
async function fetchAndPrintUrl() {
    // ...
}

这个异步函数 fetchAndPrintUrl 用于获取一个 URL,并返回其 JSON 响应中的 socks5 代理信息。

  • const url = '获取json返回的socks5的代理';:这里应该是一个实际的 URL,用于请求 socks5 代理信息。
  • const response = await axios.get(url);:使用 axios 库发起 GET 请求,获取 URL 的内容。
  • return response.data:返回响应的数据部分。
  • catch (error) { ... }:捕获并处理任何错误。

3. 写一个实际调用方法的方法

javascript 复制代码
async function new_get_token(ak, sk, lujin, url, appid, code) {
    // ...
}

这个异步函数 new_get_token 用于发送一个特定的 HTTPS 请求,并返回其响应。

  • 参数包括 ak(Access Key),sk(Secret Key),lujin(路径),url(请求的 URL),appidcode(应用程序特定的参数)。
  • encryption_data2(...):这看起来是一个自定义函数,用于生成请求的头部信息。
  • fetchAndPrintUrl():调用前面定义的函数来获取代理信息。
  • const agent = new SocksProxyAgent(socksProxyUrl, { ... }):创建一个代理代理,用于发送请求。
  • const options = { ... }:设置请求的配置信息。
  • let response = await httpsRequest(options, body);:使用前面定义的 httpsRequest 函数发起请求。
  • return response.data;:返回请求的响应数据。
  • catch (error) { ... }:捕获并处理任何错误。
相关推荐
codingWhat8 小时前
整理「祖传」代码,就是在开发脚手架?
前端·javascript·node.js
ServBay8 小时前
Node.js、Bun 与 Deno,2026 年后端运行时选择指南
node.js·deno·bun
码路飞15 小时前
Node.js 中间层我维护了两年,这周终于摊牌了——成本账单算完我人傻了
node.js
None3212 天前
【NestJs】使用Winston+ELK分布式链路追踪日志采集
javascript·node.js
Dilettante2582 天前
这一招让 Node 后端服务启动速度提升 75%!
typescript·node.js
Mr_li2 天前
NestJS 集成 TypeORM 的最优解
node.js·nestjs
Jony_2 天前
高可用移动网络连接
网络协议
UIUV2 天前
node:child_process spawn 模块学习笔记
javascript·后端·node.js
chilix3 天前
Linux 跨网段路由转发配置
网络协议
前端付豪3 天前
Nest 项目小实践之注册登陆
前端·node.js·nestjs