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:
I was reading some questions and tried to use express.static()
but it didn’t work for me:
server.ts
const express = require("express"); const cors = require("cors"); const routes = require('./routes'); const app = express(); app.use(cors()); app.use(express.json()); app.use('/uploads/actions', express.static('uploads/actions')); app.use(routes); app.listen(3000);
frontend
{ topicData.map((topic) => ( <div className="topic-data" key={topic.id}> <div className="title"> <p>{topic.title}</p> </div> <div className="description"> <p>{topic.description}</p> </div> <div className="media"> {topic.images.map((image) => ( <img key={image.id} src={"/uploads/actions/" + image.image} alt="file" /> ))} </div> <div className="contribute-btn"> <button onClick={() => contributions()}>Add comments</button> </div> </div> )); }
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.