1

I am looping over an array of objects, these objects contains links to images. Some of these images return with status 403 and do not display.

Here is what I have in ejs

<% Recipes.forEach(recipe => { %>
    <div class="basis-2/12 min-w-max">
        <% if (recipe.image) { %>
        <img class="w-60 h-40 object-cover bg-slate-100 rounded-xl" src="<%= recipe.image %>" />
        <% } else { %>
        <img class="w-60 h-40 object-cover bg-slate-100 rounded-xl" src="/images/placeholder.png" /> <% } %>
    </div>
<% }) %>

The if (recipe.name) itself only check whether there is a link or not, which is always true.

How should I go for this?

200gSoft
  • 137
  • 2
  • 12

2 Answers2

1

This solution works, the recipe.image (in this case) must have a value of null

200gSoft
  • 137
  • 2
  • 12
0

You'd have to actually fetch the image on the server before rendering the page, which would slow down the loading.

If using JavaScript on the client side is possible, consider implementing the fallback there. See for example this answer: https://stackoverflow.com/a/1588899/240963

<img
  src="<%= recipe.image %>"
  onerror='this.onerror = null; this.src="/images/placeholder.png"'
/>

Alternatively you could implement a proxy on the server, and serve the fallback in case the image on the origin is not found; useful package for this is for example: https://github.com/http-party/node-http-proxy

jnv
  • 882
  • 10
  • 18