You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

前端项目获取Favicon遇404无法捕获及CORS错误解决方案咨询

问题:无法捕获DuckDuckGo Favicon API的404错误并自定义备用图标

我有一个纯前端项目,使用DuckDuckGo第三方API获取指定网站URL的Favicon。当请求不存在的虚假域名时,API会返回带默认备用图标的404错误,但我无法捕获该404触发点——现有代码的catch块始终不执行,因为API始终返回备用图标。

现有工具函数及使用方式

工具函数

export const getFaviconLink = (bookmarkLink: string) => {
    try {
        const linkHost = new URL(bookmarkLink).hostname;
        return "https://icons.duckduckgo.com/ip3/${linkHost}.ico";
    } catch {
        return "https://placehold.co/24/202124/FFF?text=>";
    }
};

使用代码

<img src={getFaviconLink(link)} className={styles.favicon} />

尝试过的其他方案

我尝试使用fetch结合Promise调用第三方API,却遇到了预期内的CORS策略错误,代码如下:

const fetchFavicon = async () => {
  try {
    const linkHost = new URL(link).hostname;
    const faviconUrl = `https://api.faviconkit.com/${linkHost}/64`;

    const response = await fetch(faviconUrl);

    if (response.ok) {
      setFaviconUrl(faviconUrl);
    } else {
      setFaviconUrl('https://placehold.co/24/202124/FFF?text=>');
    }
  } catch (error) {
    console.error('Network error fetching favicon:', error);
    setFaviconUrl('https://placehold.co/24/202124/FFF?text=>');
  }
};

我还试过img标签的onError事件,同样无效。

疑问

请问有没有可行的解决方案?是否必须创建云函数?


内容的提问来源于stack exchange,提问作者Meet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 17:48:24