如何配置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标头,但图片下载请求中不存在该标头。
问题复现步骤
- 访问https://image-aware-background.vercel.app/
- 打开开发者控制台
- 在页面上按Ctrl+V粘贴任意图片链接
- 查看控制台中的错误信息
内容的提问来源于stack exchange,提问作者Hartaithan.
相关产品推荐
相关产品推荐

