Search code examples
expresscreate-react-appimagesource

Create React App with Node / Express import images


I'm fairly new to this and taken a look through various forums. I'm trying to find the best way.

I've followed a tutorial that gives you the create-react-app boiler plate work with a node express backend. All this is working fine, where the React boiler plate is under a folder named "site" within my Node application. I then use a proxy in package.json to direct all traffic to my API... all of this seems fairly standard as there are plenty of tutorials around for this.

The trouble I have now is that I have dynamically added images and saved their paths to database. But when I pull these out as static images to be used within my React app it naturally can not find the images. All within (./public/images) of my node application.

I was looking for the best advice really or the best practice way of serving these images to my React frontend.


Solution

  • If you need to serve static files like images from ./public/images, you need to use the Express built-in static method in a middleware :

      // Top level middleware : serve static files method
      app.use(express.static(__dirname + "/public/images"));
    

    You can client access your ressources :

      http://localhost:8080/my.png
    

    More about express.static(); method