0
0

More than 1 year has passed since last update.

No 'Access-Control-Allow-Origin' header is present on the requested resource. を無理やり克服する

Posted at

概要

image.png

Access to image at 'https://{URL} from origin 'https://{ドメイン}' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

S3 に画像や動画を展開した際に、稀によく出るこのメッセージ。
ブラウザ上で表示は出来ているのに、javascriptで画像などを利用しようとするとエラーとなり、苦い思いもしたので備忘録として対応を残しておきます。

症状

  • 上記のエラーが出たり出なかったり。
  • ブラウザを変えたり、シークレットモードで表示するとエラーが出なくなったりもする。

原因

このエラーメッセージで検索すると、S3のCORS設定CloudFrontのヘッダー設定 をする
記事が多いですが、それらの設定が正常に終了しているという前提でいうと、原因はブラウザのキャッシュです。
ブラウザにキャッシュされた画像を利用した際にエラーになります。

対策

詳しい原因はさておき、対策方法。
やっていることは単純で、パラメータを変えて三回読み直しています。

image_load.js
function imageLoad(image_url) {
    let try_count = 3;
    let img = new Image();
    let original_url = image_url.split('?')[0];
    img.onload = () => {
        /* 画像の読み込みが終わった後にやりたいこと */
    };
    img.onerror = () => {
        if (try_count > 0) {
            img.src = original_url + '?' + Math.random().toString(32).substring(2);
            try_count--;
        } else {
            /* 画像の読み込めなかった後のこと */
        }
    };
    img.crossOrigin = 'Anonymous';
    img.src = image_url;
}

取り急ぎご報告まで。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0