Reputation: 421
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:
Because when I use POSTMAN and make a request to the backend, the image displays in the body:
But whenever I make a request(using fetch) for a specific image in React, nothing shows on the page:
Here's My React Code:
Upvotes: 2
Views: 2097
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
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