我正在使用 React 创建一个基于 Yu Gi Oh! 的调色板但当我得到 url 时,我尝试将其转换为 blob 对象。但是当我请求图像时,我不断收到标题中提到的错误。
我知道 CORS 存在问题,以确保传入请求的安全性。但我查找的大多数解决方案都假设我正在从 React 向服务器发出请求。
我还尝试了 Chrome 扩展允许 Cors,它可以工作,但这只是为了测试。当我部署网站时它不会工作。
这是我认为产生问题的代码:
const getPalette = async (source) => {
const file = await fetch(source).then(r => r.blob());
const fr = new FileReader();
fr.readAsDataURL(file);
fr.onload = () => {
const img = new Image();
img.src = fr.result;
img.onload = () => {
const colorThief = new ColorThief();
const colorPalette = colorThief.getPalette(img, 9, 10);
const newPalette = colorPalette.map((color) => {
const hex = `#${toHex(color[0])}${toHex(color[1])}${toHex(color[2])}`;
return hex;
});
setPalette(newPalette);
};
};
};
CORS 是浏览保护策略。
因此,如果您想从您的站点(又名 Origin)调用此 API,则必须在(此 API 的)后端允许它。
在浏览器中禁用 CORS 策略时要小心(不应该这样做)。
有时,当您的网址错误时,它会显示 CORS。再次检查网址。