如何使用Cloud Functions for Firebase预渲染SEO页面? [英] How to use Cloud Functions for Firebase to prerender pages for SEO?

查看:63
本文介绍了如何使用Cloud Functions for Firebase预渲染SEO页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于Firebase的云功能文档此处指出,可以使用云功能来完成此操作-

The Cloud Functions for Firebase documentation here states that this can be done using cloud functions -

为单页应用程序进行预渲染以改善SEO.这样,您就可以创建动态元标记,以便在各种社交网络之间共享.

Prerendering for single page apps to improve SEO. This allows you to create dynamic meta tags for sharing across various social networks.

我有2个问题:

  • 有人可以举例说明如何实现预渲染吗?

  • Can someone explain with an example how pre-rendering is achieved?

如何与Firebase托管一起使用?假设我在xyz.com/salon/43处有一个网页,在Firebase托管中,我有一个salon.html来响应此请求.现在,为了能够进行渲染,我是否应该从托管转为渲染网页的云功能?换句话说,我来自

How does this work in conjunction with Firebase Hosting? So let's say I have a webpage at xyz.com/salon/43 and in Firebase hosting I have a salon.html which is served in response to this request. Now in order to be able to prerender should I move from hosting to a cloud function which renders the webpage? In other words do I go from

"rewrites": [{
    "source": "/salon/*",
    "destination": "/salon.html"}]

"rewrites": [{
    "source": "/salon", "function": "salon"}]

推荐答案

两个任务: -如示例中所示,将该功能添加到您的托管重写中 -编写函数以生成html页面

Two tasks: - Add the function to your hosting rewrite as in your example - Write the function to generate an html page

本教程提供了一个很好的示例,下面的功能以较长的代码段为例:

This tutorial provides a great example, with the following function as an example from a longer snippet:

const admin = require('firebase-admin');

function buildHtmlWithPost (post) {
  const string = '<!DOCTYPE html><head>' \
    '<title>' + post.title + ' | Example Website</title>' \
    '<meta property="og:title" content="' + post.title + '">' \
    '<meta property="twitter:title" content="' + post.title + '">' \
    '<link rel="icon" href="https://example.com/favicon.png">' \
    '</head><body>' \
    '<script>window.location="https://example.com/?post=' + post.id + '";</script>' \
    '</body></html>';
  return string;
}

module.exports = function(req, res) {
  const path = req.path.split('/');
  const postId = path[2];
  admin.database().ref('/posts').child(postId).once('value').then(snapshot => {
    const post = snapshot.val();
    post.id = snapshot.key;
    const htmlString = buildHtmlWithPost(post);
    res.status(200).end(htmlString);
  });
};

这篇关于如何使用Cloud Functions for Firebase预渲染SEO页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆