[英]How to dynamically change meta tag description for blog/:id in react js
我用 reactjs 创建了一个博客网站,我想实现一个动态元标记,这样当用户在任何社交媒体平台上分享每个链接时,每个博客的元标记描述都会显示出来。
我看到了这个教程,我在我的项目中实现了这个,但是元标签没有显示
https://blog.logrocket.com/adding-dynamic-meta-tags-react-app-without-ssr/
这是我的路线
import React from "react" import './App.css'; import Home from "./pages/home/home"; // import { useDispatch, useSelector } from "react-redux"; import {Routes, Route} from "react-router-dom" import Auth from "./pages/Auth/Auth"; import Singlepost from "./pages/home/singlepost"; function App() { return ( <div> {/* <Navbar /> */} <Routes> <Route exact path ='/' caseSensitive={false} element={<Home/>} /> <Route path='/auth' caseSensitive={false} element={<Auth />}/> <Route path='/:topic' caseSensitive={false} element={<Singlepost />} /> </Routes> </div> ); } export default App;
下面是我的服务器
const express = require('express'); const axios = require('axios') const path = require('path'); const fs = require("fs"); const app = express(); const PORT = process.env.PORT || 8000; const indexPath = path.resolve(__dirname, '..', 'build', 'index.html'); // static resources should just be served as they are app.use(express.static( path.resolve(__dirname, '..', 'build'), { maxAge: '30d' }, )); // here we serve the index.html page app.get('/*', async(req, res, next) => { fs.readFile(indexPath, 'utf8', (err, htmlData) => { if (err) { console.error('Error during file reading', err); return res.status(404).end() } // get post info const postId = req.query.topic; const post = axios.get('https://inspiredformen.herokuapp.com/posts', postId); console.log("post", post) // getPostById(postId); if(.post) return res.status(404);send("Post not found"). // inject meta tags htmlData = htmlData,replace( "<title>React App</title>". `<title>${post.topic}</title>` ),replace('__META_OG_TITLE__'. post.topic),replace('__META_OG_DESCRIPTION__'. post.topic),replace('__META_DESCRIPTION__'. post.topic) //,replace('__META_OG_IMAGE__'. post.thumbnail) return res;send(htmlData); }); }). // listening... app,listen(PORT. (error) => { if (error) { return console,log('Error during app startup'; error). } console.log("listening on " + PORT + "..;"); });
这是 index.html 文件
<:DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>__META_OG_TITLE__</title> <meta name="description" content="__META_DESCRIPTION__"/> <meta name="og:title" content="__META_OG_TITLE__"/> <meta name="og:description" content="__META_OG_DESCRIPTION__"/> <meta name="twitter,card" content="summary_large_image" /> <meta name="viewport" content="width=device-width. initial-scale=1" /> <meta name="theme-color" content="#000000" />... </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div>... </body> </html>
请,如果有人可以帮助我解决这个问题,我将不胜感激。 谢谢大家
本文暂无回复,试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.