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

如何配置Vite服务器CORS以解决图片加载时的跨域错误

Vite/Vue 3 图片加载CORS问题

错误信息

从源'https://my-web-app-url.com'访问'https://website.com/image-url.jpg'的图片已被CORS策略阻止:请求的资源上不存在'Access-Control-Allow-Origin'标头。

相关代码

图片加载函数

const imageLoader = (image: HTMLImageElement, url: string): Promise<HTMLImageElement> => {
  return new Promise((resolve, reject) => {
    image.crossOrigin = "Anonymous";
    image.src = url;
    image.onload = () => resolve(image);
    image.onerror = () => reject(image);
  });
};

Canvas创建函数

const createCanvas = async (url: string): Promise<CanvasObject | null> => {
  const image = new Image();
  const loaded = await imageLoader(image, url);
  const canvas = document.createElement("canvas");
  canvas.setAttribute("visibility", "hidden");
  canvas.width = loaded.width;
  canvas.height = loaded.height;
  const ctx = canvas.getContext("2d");
  if (ctx) {
    ctx.drawImage(image, 0, 0);
    return { ctx, width: image.width, height: image.height };
  } else {
    console.error("context not found");
    return null;
  }
};

已尝试的解决方案

  • 设置图片跨域属性:

    image.crossOrigin = "Anonymous"

  • 为URL添加随机查询参数(禁用图片缓存):

    image.src = url + "?" + new Date().getTime()

  • 在vite.config中启用CORS并设置origin为"*":

    server: {
      cors: { origin: "*" },
    }
    
  • 在vite.config中添加代理规则:

    server: {
      proxy: {
        "/": {
          target: "https://image-aware-background.vercel.app",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\//, ""),
        },
      },
    }
    

以上方法均未解决CORS错误,原始应用请求中能看到access-control-allow-origin标头,但图片下载请求中不存在该标头。

问题复现步骤

  1. 访问https://image-aware-background.vercel.app/
  2. 打开开发者控制台
  3. 在页面上按Ctrl+V粘贴任意图片链接
  4. 查看控制台中的错误信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:15:40