0

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.

1
  • The image path is relative to your backend server, not the frontend so the frontend is unable to find image so convert to image into data URI in backend and then sent it to frontend Commented May 16, 2022 at 11:02

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.