【问题标题】:EJS check if status is 200EJS 检查状态是否为 200
【发布时间】:2022-06-20 16:16:29
【问题描述】:

我正在遍历一组对象,这些对象包含指向图像的链接。其中一些图像返回状态 403 并且不显示。

这是我在 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>
<% }) %>

if (recipe.name) 本身只检查是否有链接,总是正确的。

我应该怎么做?

【问题讨论】:

    标签: node.js ejs


    【解决方案1】:

    在渲染页面之前,您必须在服务器上实际获取图像,这会减慢加载速度。

    如果可以在客户端使用 JavaScript,请考虑在那里实现回退。例如看这个答案:https://stackoverflow.com/a/1588899/240963

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

    或者,您可以在服务器上实现一个代理,并在找不到源图像的情况下提供回退;有用的包是例如:https://github.com/http-party/node-http-proxy

    【讨论】:

      【解决方案2】:

      此解决方案有效,recipe.image(在这种情况下)的值必须为 null

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 2018-05-01
        • 2018-12-01
        • 1970-01-01
        • 2017-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多