0

hey guys what if image not found in api..how we can set default image if there is no image resouce in api..how we can handle 404 error in javascript

function createNode(element) {
  return document.createElement(element);
}

var apiLink = "https://api_link_is_here";

fetch(apiLink)
  .then((response) => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error("Something went wrong");
    }
  })
  .then((resData) => {
      const uiDesing = resData.websites[0];
      
      uiDesing.forEach((element) => {
        // card logo
      const cardLogo = createNode("div");
      cardLogo.setAttribute("class", "card_logo");
      const img = createNode("img");
      img.src = element.logo;
      
      card.appendChild(cardLogo);
      cardLogo.appendChild(img);
          });
    });

enter image description here

Vicky Pawar
  • 35
  • 2
  • 8
  • 2
    Well, there is a difference between *image not found* and *no image source provided*. `img.onerror = function(){this.onerror = null; this.src = 'default.png'}`. – Lain Jul 16 '20 at 12:24

2 Answers2

2

HTML img tag throws console error when no image found. So you can set onerror event when no image loaded.

<img src="yourImageURL" onerror="this.src=defaultimageURL">
Ravi Khunt
  • 262
  • 2
  • 8
1

Image not found

If you do not know whether the image acutally exists (while having its source), you can use the onerror() event of img.

img.onerror = function(){
    this.onerror = null;
    this.src = 'default.png'
};

I would recommend to add a function in the onerror to actually flag the image as invalid. To remove the source and/or contact the owner. Else it keeps making unnecessary requests each time.

Image source not provided

If you have no source or know beforehand that it is invalid, just do not assign it or assign an alternative.

img.src = element.logo || 'default.png';

Combination

In the end, both can be combined.

img.src = element.logo || 'default.png';
img.onerror = function(){
    //REM: Feedback to server that this source could not be reached..
    //..
    this.onerror = null;
    this.src = 'default.png'
};

Inline

Do not forget to reset the onerror event.

<img src="404.png" onerror="this.onerror=null;this.src='default.png'">
Lain
  • 3,657
  • 1
  • 20
  • 27