I want to load the sliding images in a web app and for that I’m using Bootstrap carousel. Fetched the images from the backend. The images are stored in the images state. Below is the JSON format of the data getting fetched.
images:[
{
SNO:'1',
NAME:'image.jpg',
PIC_NAME:'image'
}
]
When the images are uploaded, they are stored in a special folder in Nodejs, and from there, I’m extracting the images using an endpoint. Below is the Nodejs Code for that
images.get('/Images/getImages/:slug', function(req, res) {
var options = {
root: path.join(__dirname, '/images')
}
res.sendFile(req.params.slug, options);
})
And below is the ReactJs code for fetching and showing the image in the web app:
import React, { useState, useEffect } from "react";
import './landingPage.css'
import Instance from "../Axios/Instance";
const Carousal = () => {
const [images, setImages] = useState([]);
useEffect(() => {
fetchImages();
}, [])
async function fetchImages() {
const result = await Instance.get('/carousalimages/getImages');
setImages(result.data);
}
console.log(images);
return (
<React.Fragment>
<div id="carouselExample" class="carousel slide">
<div class="carousel-inner">
{
images.map((pic) => {
return (
<div class="carousel-item">
<img src={`http://localhost:1200/Images/getImages/${pic.NAME}`} class="d-block w-100" alt={`${pic.PIC_NAME}`} />
</div>
)
})
}
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExample" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExample" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</React.Fragment>
)
}
export default Carousal;
But don’t know why the images are not loading in the app. Please help and explain.
Also, I’m using the endpoint to fetch the images in img src like the below code
<img src={`http://localhost:1200/Images/getImages/${pic.NAME}`} class="d-block w-100" alt={`${pic.PIC_NAME}`} />
If there is a better way, please suggest.
2
Answers
you may import images like this
or
I doubt the network error between the client and the server. As I assume the server runs from the different port, it should allow CORS config from the port where your react app is running (presumably 3000). You will easily figure out by checking out the dev tool especially the console tab.
Why don’t you just store images in your react app static folder? Are images created dynamically everytime?