Bot通过Rendertron与Firebase中间件获取PWA时Cloud Function报错
Rendertron + Firebase Cloud Function 谷歌移动友好测试失败问题排查与解决
问题场景
已在GCP部署Rendertron实例,Firebase上配置Cloud Function作为中间件,使用谷歌移动友好测试时,测试显示「URL对谷歌不可用,无法测试」,同时Cloud Function日志出现以下错误:
2022-08-23T15:49:48.486178Zappi83gp1p4qz98 Unhandled rejection Error 2022-08-23T15:49:48.490217Zappi83gp1p4qz98 FetchError: redirect location header missing at: https://rendertron-creatillo.ey.r.appspot.com/render/http://creatillo.com/post/how-its-made-hurth-6-march-2208 at ClientRequest.<anonymous> (/workspace/node_modules/node-fetch/index.js:152:13) at ClientRequest.emit (events.js:203:15) at ClientRequest.EventEmitter.emit (domain.js:466:23) at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:565:21) at HTTPParser.parserOnHeadersComplete (_http_common.js:111:17) at TLSSocket.socketOnData (_http_client.js:451:20) at TLSSocket.emit (events.js:198:13) at TLSSocket.EventEmitter.emit (domain.js:466:23) at addChunk (_stream_readable.js:288:12) at readableAddChunk (_stream_readable.js:269:11) Debug 2022-08-23T15:49:48.495068257Zappi83gp1p4qz98 Function execution took 11324 ms. Finished with status: crash Error 2022-08-23T15:49:48.581883Zappi83gp1p4qz98 Error: Process exited with code 16 at process.on.code
当前爬虫服务核心代码:
app.get('*', (req, res) => { const botResult = checkForBots(req.headers['user-agent']); if (botResult) { const targetUrl = generateUrl(req); fetch(`${FIREBASE_CONFIG.rendertron.server}/render/${targetUrl}`) .then(function(res) { return res.text(); }).then(function(body) { res.set('Cache-Control', 'public, max-age=300, s-maxage=600'); res.set('Vary', 'User-Agent'); res.send(body.toString()); }); } else { res.send(pwaShell()); } });
问题核心
日志中的*FetchError: redirect location header missing*是关键,结合你发现的Rendertron请求HTTP URL的情况,问题根源在于:目标站点强制HTTPS跳转,但Rendertron在处理HTTP→HTTPS重定向时,因头信息缺失导致请求失败;同时代码未处理Promise异常,引发进程崩溃。
解决方案
- 强制生成HTTPS目标链接:修改
generateUrl函数,确保生成的targetUrl是HTTPS协议,避免触发站点的HTTP重定向逻辑。 - 添加错误捕获逻辑:当前代码未处理fetch请求的异常,导致Unhandled rejection引发进程退出,必须补充catch块:
fetch(`${FIREBASE_CONFIG.rendertron.server}/render/${targetUrl}`) .then(function(res) { return res.text(); }).then(function(body) { res.set('Cache-Control', 'public, max-age=300, s-maxage=600'); res.set('Vary', 'User-Agent'); res.send(body.toString()); }).catch(function(err) { console.error('Rendertron渲染请求失败:', err); // 异常时返回PWA Shell,避免请求中断 res.status(500).send(pwaShell()); }); - 显式配置重定向处理:给fetch请求添加重定向参数,确保正确跟随重定向:
fetch(`${FIREBASE_CONFIG.rendertron.server}/render/${targetUrl}`, { redirect: 'follow', // 显式指定跟随重定向 follow: 5 // 限制最大重定向次数,避免死循环 }) - 验证Rendertron可用性:直接访问Rendertron实例拼接HTTPS目标链接的地址,确认能正常返回渲染后的HTML,排查Rendertron本身的配置问题。
- 检查URL拼接正确性:确认
FIREBASE_CONFIG.rendertron.server末尾没有多余斜杠,避免拼接出错误格式的URL。
内容的提问来源于stack exchange,提问作者Lorant
相关产品推荐
相关产品推荐

