Skip to content
Advertisement

ReactJS cannot display image from backend folder using node.js

I’m new in React.js and I have some data (actions) coming from database. Every action has an array of images.

I cannot display the images in image tag. Images are stored in a the backend folder structure like below:

folders

I was reading some questions and tried to use express.static() but it didn’t work for me:

server.ts

JavaScript

frontend

JavaScript

I tried usgin <img key={image.id} src={"http://localhost:3333/uploads/actions/" + image.image} alt="file" /> but it didn’t work too. What should be the correct “react way” of doing this?

Advertisement

Answer

Are you serving your react app with the express or you are using webpack-dev-server/create-react-app? If your front-end is served from a different port (ex. 4000) you should specify the absolute path as you did. However, you will get the cors error and it will be necessary to enable it with cors middleware: https://expressjs.com/en/resources/middleware/cors.html The second option is to use proxy to run backend and frontend on the same domain.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement