My api is fetching an image but i cant seem to display it into ReactJs.
The api :
[
{
"id": 1,
"vessel_component_count": 3,
"vessel_inventory_category_count": 0,
"name": "Aylah",
"imo": "Aylah123",
"image": "/media/vessel_image/aylah.jpg"
},
{
"id": 2,
"vessel_component_count": 1,
"vessel_inventory_category_count": 0,
"name": "Sinaa",
"imo": "sinaa123",
"image": null
},
{
"id": 3,
"vessel_component_count": 0,
"vessel_inventory_category_count": 0,
"name": "Amman",
"imo": "amman123",
"image": "/media/vessel_image/amman.jpg"
}
]
the code in react
parent component Homescreen.js :
function HomeScreen() {
const [vessels, setVessels] = useState([]);
useEffect(() => {
async function fetchVessels() {
const { data } = await axios.get(
"http://127.0.0.1:8000/api/vessels/info"
);
setVessels(data);
}
fetchVessels();
}, []);
return (
<div>
Fleet vessels :
<div className="fleet-vessels-info">
{vessels.map((vessel) => (
<VesselCard vessel={vessel} />
))}
</div>
</div>
);
}
export default HomeScreen;
the child component VesselCard.js :
function VesselCard({ vessel }) {
return (
<div className="fleet-vessel-card">
{vessel.name}
<img src={vessel.image} />
</div>
);
}
export default VesselCard;
getting everything else like the name and imo is working fine except the image.
CodePudding user response:
It looks like, since the image paths are returned relatively by your backend, you're trying to fetch them from your frontend server instead.
eg. If your backend is "backend.com" and your frontend is "frontend.com" (i.e. where your localhost/react application server is running),
then it's searching for 'frontend.com/media/vessel_image/amman.jpg'
when it looks like it should be searching for 'backend.com/media/vessel_image/amman.jpg'
You can see this if you check your Dev tools > Network tab
and see that it's unable to find the images.
CodePudding user response:
The path of image you provided is relative. Either provide absolute path of image or store these images in public folder. public > media > vessel_image