首页 > 解决方案 > 使用 Express Backend 动态更改 React Js 应用程序的元标记

问题描述

我一直在研究动态更改我的 react Js 应用程序的元标记。我尝试了很多解决方案,例如 Helmet,但我没有成功。如果有人能给我一个关于这项任务的清晰算法,我会很高兴。我有两个后端,一个在 Express 中,另一个在 PHP 中。我专门为此任务创建了 Express 后端,但是当我将链接分享到 Facebook 等其他平台时,我还没有成功更改元标记。

我目前的实施。前端:我的 Index.html 里面 public 有

    <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" />

快速后端

const express = require('express');
const cors = require("cors");
const path = require('path');
const fs = require('fs');
const app = express();
app.use(cors());
const port = process.env.PORT || 2800;

app.use('/api/dynamicmeta', (req, response)=>{
    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, 'Contact Page');
      data = data.replace(/\$OG_DESCRIPTION/g, "Contact page description");
      result = data.replace(/\$OG_IMAGE/g, 'https://i.imgur.com/V7irMl8.png');
      response.send(data);
    });
});

app.use(express.static(path.resolve(__dirname, './build')));
app.get('*', function(request, response) {
  const filePath = path.resolve(__dirname, './build', 'index.html');
  response.sendFile(filePath);
});

app.listen(port, () => console.log(`listening on port ${port}!..`));

module.exports = {
  app
}

在这一点上,我对如何继续感到困惑,因为我的构建标题没有改变。

标签: javascriptreactjsexpressreact-reduxmeta-tags

解决方案


推荐阅读