Here is my backend route, i'm getting a file name as parameter from URL and accessing the file. how do I access the data passed from this route into my frontend react.js??
router.route("/list/:filename").get((req, res) => {
fs.readFile("./api/assignment_data/" req.params.filename ".json", function read(err, data) {
if (err) {
throw err;
}
const content = data;
foundFile => res.json(foundFile)
console.log("sent")
})
})
In my frontend I am doing something like this,
useEffect(() => {
fetch("/list/:filename").then(res => {
if (res.ok) {
console.log("all ok")
return res.json()
}
}).then(jsonRes => setMetrics(jsonRes))
})
CodePudding user response:
I think you are doing everything right as long as you are sending correct file name which in react you have marked as :filename
(like data.json) if you are doing that it should work, I just dont understand this line foundFile => res.json(foundFile)
because you are not sending any file in return maybe you can try replacing that line with res.status(200).json({data});
this should work
CodePudding user response:
You are using useeffect wrong this way it will infinitely run rerendering your application everytime there is any change in DOM, so do this
useEffect(() => {
fetch("/list/:filename").then(res => {
if (res.ok) {
console.log("all ok")
return res.json()
}
}).then(jsonRes => setMetrics(jsonRes))
},[])
this way it'll only run once