You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过Squid代理使用Axios请求谷歌时随机出现503/502错误的原因

随机出现502/503错误的原因及解决建议

背景信息

你已配置系统环境变量:

export HTTPS_PROXY="<username>:<password>@<proxy_ip>:<proxy_port>"

并使用以下Axios代码请求谷歌:

const instance = axios.create({
    httpsAgent: new https.Agent({
        rejectUnauthorized: false,
    })
});

instance.get('https://www.google.com')
    .then((response) => {
        console.log(response.status);
    })
    .catch((error) => {
        console.error('Error:', error.response.status);
    });

请求随机返回502/503错误,而非预期的200,可能的原因及解决方法如下:


1. Axios未正确使用代理配置

Node.js环境中,Axios默认不会自动读取HTTPS_PROXY环境变量,当前代码仅关闭了证书验证,未配置代理相关参数,导致请求可能未通过Squid代理发送,或代理传递过程中出现异常,引发随机错误。

解决方法:
使用https-proxy-agent库明确配置代理,步骤如下:

  • 安装依赖:
    npm install https-proxy-agent
    
  • 修改代码配置代理:
    const axios = require('axios');
    const { HttpsProxyAgent } = require('https-proxy-agent');
    
    // 从环境变量读取代理地址
    const proxyAgent = new HttpsProxyAgent(process.env.HTTPS_PROXY);
    
    const instance = axios.create({
        httpsAgent: proxyAgent,
        // 若需关闭证书验证,可在代理Agent中配置
        // httpsAgent: new HttpsProxyAgent({
        //   proxy: process.env.HTTPS_PROXY,
        //   rejectUnauthorized: false
        // })
    });
    
    instance.get('https://www.google.com')
        .then((response) => {
            console.log(response.status);
        })
        .catch((error) => {
            console.error('Error:', error.response?.status || error.message);
        });
    

也可直接通过Axios的proxy选项手动配置认证信息:

const instance = axios.create({
    proxy: {
        protocol: 'https',
        host: '<proxy_ip>',
        port: <proxy_port>,
        auth: {
            username: '<username>',
            password: '<password>'
        }
    },
    httpsAgent: new https.Agent({
        rejectUnauthorized: false
    })
});

2. Squid代理服务器自身问题

Squid代理可能存在以下问题导致随机错误:

  • 连接数或带宽达到上限,触发503(服务不可用);
  • 代理与谷歌服务器的连接不稳定,出现超时或中断,返回502(网关错误);
  • 代理认证会话超时,导致请求偶尔认证失败。

解决方法:

  • 查看Squid日志(通常在/var/log/squid/access.log和cache.log),排查是否有连接超时、资源耗尽或认证失败的记录;
  • 调整Squid配置文件中的maxconn、cache_mem等参数,提升代理的负载能力;
  • 确认代理服务器的认证机制是否正常,检查用户名密码是否有效,是否开启了Basic Auth支持。

3. 谷歌服务器的限流或反爬机制

谷歌会对来自同一IP(尤其是代理IP,可能被多人共用)的频繁请求进行限流,随机返回502/503错误作为反制措施。

解决方法:

  • 降低请求频率,添加随机延迟;
  • 更换代理IP,避免使用被谷歌标记的高频率代理;
  • 为请求添加合理的User-Agent头,模拟正常浏览器请求:
    instance.get('https://www.google.com', {
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
        }
    })
    

4. 网络链路不稳定

代理服务器与你的机器、代理与谷歌之间的网络链路偶尔出现丢包、延迟过高,也会导致请求失败,返回502/503。

解决方法:

  • 使用ping或traceroute测试代理服务器的连通性;
  • 尝试切换网络环境,排查本地网络是否存在波动。

内容的提问来源于stack exchange,提问作者Gokulakannan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 11:47:23