向translate.google发送GET请求时出现502 Bad Gateway错误求助
502 Bad Gateway错误排查与解决
问题背景
我定义了createOptionsFor方法生成请求配置对象,尝试连接translate.google.com,调用connect方法时触发了状态码非200的处理逻辑,返回502错误。
错误信息
RasDaRESTAPI:: Did not get an OK from the server. Code: 502 RasDaRESTAPI:: Did not get an OK from the server. Msg: Bad Gateway
代码片段
RasDaRESTAPI类
export default class RasDaRESTAPI { constructor() { this.options = undefined this.agent = new HttpsProxyAgent('http://proxy.xxxx.xx:8000'); } createOptionsFor(rasDaLayer, startDate, endDate, easting, northing, userName, password) { let auth = 'Basic ' + Buffer.from(userName + ':' + password).toString('base64'); return this.options = { agent: this.agent, protocol: rasDaRes.PROTOCOL_HTTPS, host: rasDaRes.HOST, path: encodeURI( rasDaRes.PATH ), port:8000, method:'GET', headers: { 'Content-Type': 'application/json' } }; } connect(options) { const resCallback = (response)=>{ if (response.statusCode !== 200) { console.error(debugTag,"Did not get an OK from the server. Code:",response.statusCode); console.error(debugTag,"Did not get an OK from the server. Msg:",response.statusMessage); // console.error(debugTag,"Did not get an OK from the server. options:",options); response.resume(); return; } var body = ''; response.on('data', (chunk)=>{ body = body + chunk; }); response.on('end', ()=>{ console.info(debugTag,'response-body: ',body) onResult(response.statusCode, body); }); } const req = https.request(options, resCallback); req.on('error', (err) => { console.error("problem with request.e.:", err); console.error("problem with request.e.stack:", err.stack); }); req.end(); } }
常量定义
function define(name, value) { Object.defineProperty(rasDaRes , name, { value: value, enumerable: true, writable: false }); } export let rasDaRes = {}; define('PROTOCOL_HTTPS','https:') define('HOST','translate.google.com') define('PATH','/?hl=de')
原因分析
- 端口配置错误:请求配置中手动指定了
port:8000,但HTTPS请求默认端口是443,这个设置会让请求直接访问translate.google.com:8000,而非通过代理转发到正确的443端口。 - 请求头冗余:GET请求没有请求体,却设置了
Content-Type: application/json,这种不匹配的请求头可能被代理或目标服务器判定为非法请求。 - 代理有效性问题:使用的代理
http://proxy.xxxx.xx:8000可能不支持HTTPS请求转发,或者代理地址/端口本身不可用。 - 反爬拦截:谷歌翻译有反爬机制,无合法请求头的直接请求可能被拦截,返回502错误。
解决办法
- 修正端口配置:删除请求配置中的
port:8000,让HTTPS请求使用默认的443端口,代理会自动处理转发。 - 调整请求头:移除多余的
Content-Type头,同时添加模拟浏览器的User-Agent以规避反爬,示例: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' } - 验证代理可用性:确认代理地址和端口正确,且支持HTTPS转发。如果代理需要认证,需在
HttpsProxyAgent中添加用户名密码,示例:this.agent = new HttpsProxyAgent('http://username:password@proxy.xxxx.xx:8000'); - 适配谷歌翻译规则:如果上述调整后仍有问题,可尝试使用谷歌翻译的官方API而非直接请求网页,避免反爬拦截。
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

