【问题标题】:Dynamic meta tags in server side using react服务器端使用反应的动态元标记
【发布时间】:2018-11-29 07:48:16
【问题描述】:

我正在使用 SSR 构建一个 React 应用程序。我现在必须使用动态元标记(og:title 和 og:image)实现 Facebook 共享功能。

阅读本教程https://www.kapwing.com/blog/how-to-add-dynamic-meta-tags-server-side-with-create-react-app/ 后,我可以完成我的/about/faq 页面(静态)。但是,我在/posts/:id 等动态页面上遇到了问题。

public/index.html 中,我将元数据替换为可识别的字符串:

<!-- in public/index.html -->
<title>$OG_TITLE</title>
<meta name="description"        content="$OG_DESCRIPTION" />
<meta property="og:title"       content="$OG_TITLE" />
<meta property="og:description" content="$OG_DESCRIPTION" />
<meta property="og:image"       content="$OG_IMAGE" />

然后在服务器上,我将这些字符串替换为动态生成的信息。这是一个使用 Node 和 Express 的示例路由:

app.get('/about', function(request, response) {
  console.log('About page visited!');
  const filePath = path.resolve(__dirname, './build', 'index.html')
  fs.readFile(filePath, 'utf8', function (err,data) {
    if (err) {
      return console.log(err);
    }
    data = data.replace(/\$OG_TITLE/g, 'About Page');
    data = data.replace(/\$OG_DESCRIPTION/g, "About page description");
    result = data.replace(/\$OG_IMAGE/g, 'https://i.imgur.com/V7irMl8.png');
    response.send(result);
  });
});

那么对于动态路由,/posts/:id,我该如何实现呢?

【问题讨论】:

    标签: reactjs express meta-tags server-side-rendering


    【解决方案1】:

    /about

    app.get('/posts/:id', function(request, response) {...}
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关其解决问题的方式和/或原因的附加上下文将提高​​答案的长期价值。Read this
    猜你喜欢
    • 1970-01-01
    • 2019-12-30
    • 2016-01-25
    • 2011-08-19
    • 2019-02-09
    • 2018-10-02
    • 1970-01-01
    • 2016-10-08
    • 2018-02-16
    相关资源
    最近更新 更多