使用 Fetch In ReactJs 下载图像



我正在尝试使用 reactJS 中的 fetch 下载图像。但是每当我调用该函数时,我都会面临 CORS 错误。

var image_trade_license = new Image();
image_trade_license.crossOrigin = "anonymous";
image_trade_license.src = "https://via.placeholder.com/150/92c952";
// get file name - you might need to modify this if your image url doesn't contain a file extension otherwise you can set the file name manually
var fileName_trade_license = 'trade_license';
image_trade_license.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
var blob_trade_license;
// ... get as Data URI
if (image_trade_license.src.indexOf(".jpg") > -1) {
blob_trade_license = canvas.toDataURL("image_trade_license/jpeg");
} else if (image_trade_license.src.indexOf(".png") > -1) {
blob_trade_license = canvas.toDataURL("image_trade_license/png");
} else if (image_trade_license.src.indexOf(".gif") > -1) {
blob_trade_license = canvas.toDataURL("image_trade_license/gif");
} else {
blob_trade_license = canvas.toDataURL("image_trade_license/png");
}
$("#image1").append("<a download='" + fileName_trade_license + "' href='" + blob_trade_license + "'><button>Download Trade License</button></a>");
}

我正面临此错误(发生在浏览器控制台中(-

Access to image at 'https://via.placeholder.com/150/92c952' from origin 
'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control- 
Allow-Origin' header is present on the requested resource.
via.placeholder.com/150/92c952:1 Failed to load resource: net::ERR_FAILED

首先,你有没有在 fetch 配置中设置过mode: "no-cors"?喜欢这个:

fetch('https://via.placeholder.com/150/92c952', {
method: 'POST',
mode: "no-cors"
})

如果仍然收到 CORS 错误。您可以在Chrome中禁用源策略以继续调用API,而不会使用本文出现CORS错误

或者,这篇文章可以为您提供有关Web浏览器中CORS的更多知识。

最新更新