服务器端的动态元标记呈现了React应用程序

时间:2017-01-17 19:21:02

标签: reactjs serverside-rendering

我有一个带有服务器端渲染的React应用程序。我现在必须实现Facebook / Google +共享对话框,其中 og:title og:image 动态设置为从API返回的值。

我正在使用 react-helmet 设置我的默认元标记,但是我遇到了麻烦,让它动态运行。

我尝试使用 redux-async-connect 来预取结果,这导致元标记被渲染(当我查看源代码时我可以看到它们),但Facebook和Google+都忽略了它们。

你们有没有做过这项工作的经验?

2 个答案:

答案 0 :(得分:1)

您可以像这样在文档中呈现应用:     AvroParquetFileSource<MyClassCompiled> avroParquetFileSource = new AvroParquetFileSource<MyClassCompiled>( new Path(input), Avros.records(MyClassCompiled.class) ); 而App包含你需要的所有HTML。

答案 1 :(得分:0)

基本上,在您的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);
  });
});

取自本教程:https://www.kapwing.com/blog/how-to-add-dynamic-meta-tags-server-side-with-create-react-app/