1

I'm working on a full-stack project using React, Express, and Node.

I have created a JSON file on the backend with some information such as name, description, and pictures. Here's an example:

id: 1 name: Earth description: The Earth is a planet image: images/earth.jpg

My picture is located in a public folder (inside back called "server" folder) like this:

server/data/public/images/earth.jpg

What code do I need to write on the backend to upload pictures and display them on the frontend? I have already retrieved other information from the backend and displayed it on the frontend (name, description), but the picture isn't working.

I wrote the code app.use(express.static('public'); and tried that :

app.get('/data', (req, res) => {
  const filePath = `${__dirname}/data/public/images/planetes.json`;
  const data = JSON.parse(fs.readFileSync(filePath, ));
  res.json(data);
});

But is not working.

Any suggestions ? Thank you !

3
  • I'm a bit confused why would you wanna send a .json file extension if you actually need to send an image file ? Maybe this is what you're looking for express.static middleware? Commented May 12, 2023 at 14:37
  • Because each id have their own image, so when i will map it, each image will come with their informations. Thanks, I will check the topic Commented May 12, 2023 at 17:31
  • Have you tried looking at the sendFile API that Express provides? Commented May 13, 2023 at 7:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.