我想在js + jquery中創建圖片編輯器。在第一步,我要求用戶提供圖片網址。但我遇到問題,當我嘗試加載JS內的圖像數據(生成base64圖像uri)。在控制檯中出現錯誤:… has beeb blocked by CORS policy: Access-Control-Allow-Origin …
。但我想知道爲什麼?如果在HTML文件中我創建了實例(圖片盜鏈):html <img src=...>工作,但JS圖像加載導致CORS錯誤
<img src="https://static.pexels.com/photos/87293/pexels-photo-87293.jpeg" />
瀏覽器加載圖像而沒有任何問題CORS!這裏是我的JS代碼,對於相同的圖像扔CORS問題:
function downloadFile(url) {
console.log({url});
var img = new Image();
img.onload = function() {
console.log('ok');
// never execute because cors error
// … make base64 uri with image data needed for further processing
};
img.crossOrigin = "Anonymous";
img.src = url;
}
所以,問題是 - 如何強制JS加載圖像(如HTML標籤加載它),並將其轉換爲base64 URL避免CORS問題?
https://static.pexels.com/photos/87293/pexels-photo-87293.jpeg
你在測試什麼網頁服務器? –
我沒有使用任何Web服務器 - 我打包胖客戶端應用程序:只有JS + HTML + CSS –
這是你的問題。您不能只從您的文件系統運行該文件。看看在LAMP/XAMPP或NodeJS輕量級服務器上測試/開發,例如'http-server' –