node.js - 使用 Firebase 功能作为代理服务器
问题描述
我使用托管在 firebase 上的 Vuejs 构建了一个应用程序,我最近使用 rendertron 添加了动态渲染以改进 SEO,我将 rendertron 托管在 Heroku 上。rendertron 客户端运行良好。
为了将来自 googlebot 等机器人的请求发送到 rendertron 并接收已编译的 HTML 文件,我使用了 firebase 函数,它检查用户代理,如果是机器人,则将其发送到 rendertron 链接,如果不是,则获取应用程序并重新发送结果。
这是功能代码:
const functions = require('firebase-functions');
const express = require('express');
const fetch = require('node-fetch');
const url = require('url');
const app = express();
const appUrl = 'khbich.com';
const renderUrl = 'https://khbich-render.herokuapp.com/render';
function generateUrl(request){
return url.format({
protocol:request.protocol,
host:appUrl,
pathname:request.originalUrl
});
}
function detectBot(userAgent){
let bots = [
"googlebot",
"bingbot",
"facebookexternalhit",
"twitterbot",
"linkedinbot",
"facebot"
]
const agent = userAgent.toLowerCase()
for(let bot of bots){
if(agent.indexOf(bot)>-1){
console.log('bot-detected',bot,agent)
}
}
}
app.get('*', (req,res)=>{
let isBot = detectBot(req.headers['user-agent']);
if(isBot){
let botUrl= generateUrl(req);
fetch(`${renderUrl}/${botUrl}`)
.then(res => res.text())
.then(body=>{
res.set('Cache-Control','public','max-age=300','s-maxage=600')
res.set('Vary','User-Agent');
res.send(body.toString())
})
}
else{
fetch(`https://${appUrl}`)
.then(res=>res.text())
.then(body=>{
res.send(body.toString())
})
}
});
我将该函数用作 Firebase 托管的入口点,因此每当有人进入应用程序时都会调用它。
我在firebase仪表板上检查它是否工作,我注意到它因超过每100秒配额的请求数而崩溃,我检查时用户不多,函数调用在一分钟内达到370次调用.
我不明白为什么我一次有大量的调用,我在想也许是因为如果用户代理不是机器人,我正在获取网站,那么函数被重新调用导致无限循环调用,但我不知道这是否真的是为什么?
如果它是一个无限循环,我如何在不重新调用函数的情况下将用户重定向到他们输入的 url?重定向会起作用吗?
解决方案
推荐阅读
- image - 从清单构建 Docker 映像
- reactjs - 当我尝试将 API 调用作为道具从一个组件传递到另一个组件时,承诺未决
- html - 我怎样才能让我的图像环绕我的文字?
- ecmascript-6 - Jasmine 测试依赖项:不能在模块外使用 import 语句
- stackdriver - Opencensus 高级聚合
- python - Python asyncio await-for timeout 不适用于无限任务
- python - QWidget 不接受大于大约 23000 的 setFixedSize 值
- ios - objective-c : 2 个 viewControllers 之间的自定义 segue 转换
- laravel - 使用 Guzzle 客户端获取 API 数据
- angular - Angular 10:下一次调用后订阅 observable 不会触发