reactjs - 如何从 Express 服务器上的 React 应用程序获取数据以使用从 API 获取的数据更新元标记
问题描述
我正在使用一个 React API,我使用 API 调用来获取数据。我需要在 Express 服务器中可以访问这些数据,以便我可以更新元标记,但我还没有找到实现这一目标的方法。这是 URL 结构:
/post/slug
我获取所有数据的反应组件:
const Post = () => {
const [post, setPost] = useState(null)
const { slug } = useParams();
useEffect(() => {
const urlFetch = 'URL' + slug;
fetch(urlFetch )
.then(response => response.json())
.then(data => setPost(data));
}, [slug]);
if (!post) {
return (
<>
//Loader
</>
)
}
return (
<>
//component
</>
);
}
export default Post;
为了动态更改元标记,请使用 Express,但我不知道如何实现这一点。这是 server.js 文件:
const express = require('express');
const path = require('path');
const fs = require('fs');
const util = require('util');
const PORT = 5000;
const app = express();
app.get("/", async (req, res) => {
const filePath = path.resolve(__dirname, "./client/build", "index.html");
await fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
return console.log(err);
}
data = data
.replace(/__TITLE__/g, "Home title")
.replace(/__DESCRIPTION__/g, "Home description");
res.send(data);
})
})
app.get('/:type/:slug', async (req, res) => {
const filePath = path.resolve(__dirname, "./client/build", "index.html");
await fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
return console.log(err);
}
data = data
.replace(/__TITLE__/g, "Post title")
.replace(/__DESCRIPTION__/g, "Post description");
res.send(data);
})
});
app.use(express.static(path.resolve(__dirname, "./client/build")));
app.listen(PORT, () => {
console.log(`Server is listening to port: ${PORT}`);
})
解决方案
您可以简单地通过使用 React Helmet 更改元标记,它允许您在运行时直接更新元标记...
例如:
<head>
<title>needed Title</title>
<meta name="description" content="description component">
您可以根据需要在每个组件中使用它,并通过状态动态更新它...
您还可以构建 html 组件以将其作为包装器处理:
function HTML () {
const htmlAttrs = helmet.htmlAttributes.toComponent();
const bodyAttrs = helmet.bodyAttributes.toComponent();
return (
<html {...htmlAttrs}>
<head>
{helmet.title.toComponent()}
{helmet.meta.toComponent()}
{helmet.link.toComponent()}
</head>
<body {...bodyAttrs}>
<div id="content">
// React stuff here
</div>
</body>
</html>
);
}
因此,现在当您发布或获取元标记时,您将获取动态的元标记,并嵌套在 express 上替换,您只需更新代码以获取标记并将其分配给 react..如果您需要在元中发布数据,只需从状态并将其放入发布请求中..
更多详情:这里
推荐阅读
- css - Edge 中的 CSS 问题 - 下划线
- csv - Arduino 加速度计输出处理到 CSV 文件
- amazon-redshift - 如何通过 SVV_TABLE_INFO 中的 skew_sortkey1 估计 sortkey?
- scala - 将列表作为单个函数参数传递
- react-native - navigator.geolocation:: Location request timed out issue React Native
- node.js - npm 错误“Keccak 绑定编译失败。” 在安装松露时
- javascript - Appium测试android应用程序时如何修复错误“TypeError:client.click不是函数”?
- sql - 用于将 Redshift 数据移动到 Azure SQL 数据仓库的分发方法
- list - 带有 digitalWriteFast 的多个电机
- java - 如何修复“HTTP 状态 404”Spring MVC