George Marwanqana
George Marwanqana

Reputation: 421

How to display static files served from backend (ExpressJS) onto React Page?

I'm building a web app using React(frontend) and Node/Express(backend). Now, I've stored some images in a 'public' folder(in the backend--express). My goal is to fetch the images that are stored on the server and display them on my frontend page. Sort of like when you fetch JSON data from the server/database, convert it to JSON and display the data onto the HTML page.

I'm using express.static() middleware to serve the images that are in the backend. My problem is:

  1. How do I send the images back to the frontend, and make them display onto the HTML page(React Component)?

Because when I use POSTMAN and make a request to the backend, the image displays in the body: enter image description here

But whenever I make a request(using fetch) for a specific image in React, nothing shows on the page: enter image description here

Here's my Express codeenter image description here

My backend folder Structure: enter image description here

Here's My React Code:

enter image description here

Upvotes: 2

Views: 2097

Answers (2)

Harsh
Harsh

Reputation: 15

As already mentioned in other answers here that it is not advisable to use fetch() API for this purpose. I'll try to add a bit more context to this. Even I have been facing a very similar problem, the only difference being my frontend was in vanilla js and I was trying to display an HTML file.

The thing with fetch() is that, whenever you call some route using the fetch() API, then whatever you try to return through that route (in this case the static files) gets returned to your fetch() call. Now, fetch() does not have any in-built functionality to display anything on the frontend that has been sent to it.

Therefore the best bet is to not use fetch() at all for this purpose, and simply use the <img /> tag. This should solve the problem.

Upvotes: 0

sachin
sachin

Reputation: 1117

Don't do fetch for image.
just add an image tag with src as the path of the file like this :

<img src="http://localhost:3000/GlobalSearch/ClubSearch/PlayerStats/Fisher.jpg" />

This should solve your problem.

Upvotes: 3

Related Questions