I am learning react and express and I was trying to make a simple blog website with React as my Front end and Express server for the backend.
For the Express Server this is my code:-(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...");
});
And this is something I was able to create by using online sources for React:-(App.jsx)
import React from "react";
function App() {
const [data, setData] = React.useState(null);
How should I pass the postname typed in url in the below code?For example I type 'localhost:3000/posts/day1' so that I can find info about post named day1 and render that blog post
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;
I hope I am not approaching it in a wrong way.