Reputation: 785
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?
Upvotes: 1
Views: 2676
Reputation: 51
You could just create a folder like uploads instead of nesting actions in uploads folder. You can then view the image in the browser through this url localhost:3333/uploads/1616437561024-foto54.jpg
// Function to serve all static files
app.use("/uploads", express.static("uploads"));
Upvotes: 2
Reputation: 347
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.
Upvotes: 2
Reputation: 2131
Instead of this:
app.use('/uploads/actions', express.static('uploads/actions'));
use this:
// don't forget to require the "path" module before that
const path = require('path');
app.use('/uploads/actions', express.static(path.join(__dirname, 'uploads/actions')));
Actually with path.join(...) you'll mention the full path of your image file.
Upvotes: 1