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 !

Aleksandar
  • 844
  • 1
  • 8
  • 18
Blake
  • 21
  • 2
  • 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](https://stackoverflow.com/a/65176583/12737879) is what you're looking for `express.static` middleware? – Aleksandar May 12 '23 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 – Blake May 12 '23 at 17:31
  • Have you tried looking at the `sendFile` [API](http://expressjs.com/api.html#res.sendFile) that Express provides? – roksui May 13 '23 at 07:08

0 Answers0