【发布时间】:2021-09-01 15:07:45
【问题描述】:
我正在学习 react 和 express,我正在尝试制作一个简单的博客网站,其中 React 作为我的前端,Express 服务器作为后端。
对于 Express 服务器,这是我的代码:-(app.js)
const express=require('express');
var _ = require('lodash');
const app=express();
app.use(express.static(__dirname));
app.get("/",function(req,res){
res.sendFile(__dirname+"/client/public/index.html");
});
app.get("/api",function(req,res){
res.send({heading: "'Hello World"});
});
app.get("/posts/:postName",function(req,res){ //---->want to get data linked with the 'postName'
let post=req.params.postName;
console.log(post);
res.json({postName:post});
});
app.listen(8080,function(){
console.log("Server is running...");
});
这是我通过使用 React 的在线资源创建的东西:-(App.jsx)
import React from "react";
function App() {
const [data, setData] = React.useState(null);
我应该如何在下面的代码中传递在 url 中输入的帖子名称?例如,我输入 'localhost:3000/posts/day1' 以便我可以找到有关名为 day1 的帖子的信息并呈现该博客帖子
React.useEffect(() => {
fetch("/posts/")
.then((res) => res.json())
.then((data) => setData(data.users));
}, []);
return (
<div className="App">
<header className="App-header">
<p>{!data ? "Loading..." : data}</p>
</header>
</div>
);
}
export default App;
我希望我没有以错误的方式接近它。
【问题讨论】:
-
这能回答你的问题吗? Read the current full URL with React?