How do I Display Images in React which are downloaded as Files & saved in a Folder on the Server with the Filepath stored in my Database?

Viewed 658

Short Setup, Problem & Code Summary

Setup

React.js, Node.js/Express.js & PostgreSQL.

I scrape an ImageUrl of a Book, download and store it in a File in an Image Folder with Node.js and store the Filepath in my postgreSQL Database AND I would like to fetch and display the Image in an <img /> tag on my React frontend.

Problem

The Image I Fetch from my Database through my API doesn't get displayed, eventhough I can console.log the Image Object in the devtool-console and even make a succesful Postman request with the Image-Object as JSON response. Furthermore I can get the image even be displayed if I go to localhost:3001/image-193x278.png. My <img /> Tag has even the right Img src attribute displayed in the devtools (images\image-193x278.png)

In the devtool-console I get the following error: GEThttp://localhost:3002/images/image-193x278.png [HTTP/1.1 404 Not Found 0ms]

(Note: My Frontend runs on localhost 3002 while my server & frontend are running concurrently with a proxy on 3001, but that isn't the causing Problem here)

Code

React Code

const [image, setImage] = useState([]);

  useEffect(() => {

    async function fetchData() {
      const response = await fetch('http://localhost:3001/test', {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        }
      })
      const data = await response.json();
      console.log(data);
      setImage(data);
    }
    fetchData();

  }, []);

I tried to get it displayed in two different ways:

<img className={css(styles.Image)} src={image.test_images} alt="" />

{image.map((img) => 
<img className={css(styles.Image)} src={img.test_images} alt="" />)}

Server-Side

app.get('/test', async (req, res) => {
    try {
        const image = await testdb.query('SELECT * FROM test_table');
        res.json(image.rows);
    } catch (err) {
        console.error(err);
    }
})

I serve an Express Static File

app.use(express.static('images'));

I even tried two additional varients just in case

app.get('/test', express.static(__dirname + '../images'));
app.use(express.static('../images'));

Still with no succes. I hope i could make myself understood as good as possible and I would be extremely thankful for every help thrown out my way.

1 Answers

The problem is with your static folder. The static files will be available at localhost:3002/:filename.

If you want to make it work under /images path, then you can add the path to the static declaration like

app.use('/images', express.static('images'))

Then you can hit the localhost:3002/images/:filename.

You can find the documentation here: https://expressjs.com/en/starter/static-files.html

Related