Reputation: 167
I am working with ReactJS, and I need to serve some pictures in my front end, I can't do it in the following way <img alt="" src={process.env.PUBLIC_URL + image + ".png" } />
because I will serve more than 2 pictures starting with a specific keyword, so I am thinking to do like this
dir= '../../public/images/'
files= fs.readdirSync(dir)
for (const file of files) {
if(file.startsWith(keyword))
{
setPictureName(dir+file+ ".png")
}
}
But unfortunately I can't use the 'fs' module in the client side, so I am lost, should I do the processing in the back end then send those pictures ? If yet how to do it, and I would be happy to receive other suggestions.
Upvotes: 1
Views: 13046
Reputation: 1
first you must config main file and put this code
#app = express();
this.#app.use(express.static(path.join(__dirname, "public"));
and in front side
<img src={product.imagesUrl} className="w-28" alt="phone image" /
and your model must be
product.virtual("imagesURL").get(function () {
return this.images.map(
(image) =>
`${process.env.BASE_URL}:${process.env.APPLICATION_PORT}${image}`
);
});
Upvotes: 0
Reputation: 1
On react frontend:
<img src={`http://localhost:3000/images/image1.png`} alt="" />
I'm hoping you have already set your static folder on the node backend.. If not:
app.use(express.static('public'));
Folder structure on the backend: public > images > image1.png
Upvotes: 0
Reputation: 358
Assuming that you are using express at your backend just serve the files as static from public or whatever folder you want.
app.use('/static', express.static('public'))
then get your files by calling urls like
http://localhost:3000/{your_image_name}.jpg
Upvotes: -1