2

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

4
  • Why use fetch to get the image ?😑 it’s an img file so just use the ‘img tag’ Commented Sep 1, 2022 at 13:31
  • i want the images from the sever to show in the frontend how do i do that? Commented Sep 1, 2022 at 14:16
  • What’s the response you get when your fetch the data Commented Sep 1, 2022 at 14:47
  • Please see How to Ask. Code doesn't belong in images. Commented Sep 1, 2022 at 16:38

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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.