LoginSignup
34
25

More than 5 years have passed since last update.

CORSエラー対策

Posted at

概要

ローカルだけで手っ取り早くcanvas系のjsを練習したかっただけなのにcross-orignエラーが出たのでついでに調べた

エラー例

Access to Image at 'file:///Users/~~~.png' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.

CORSについて

外部からの静的ファイルなどを読み込む制限、Chromeだとローカルからでもcanvasからファイルの読み込みができなくなってた

概要はこちらに詳しくまとめられてました
HTML5 における CORS について

ローカル環境(html+js)内でできる対応策のみ調べた

jsを使う場合

  var url = '使いたい外部URL';
  var img = new Image();
  img.crossOrigin = 'anonymous';
  img.src = url;
  img.onload = function() {
    imgを引数にしてイメージの読み込み
  };

参考:MDN

※pixijsのfromImageにはcrossorignオプションがあった
pixijs公式github
使い方例

  texture = new PIXI.Texture(PIXI.BaseTexture.fromImage(imageUrl, crossorigin));
  PIXI.TextureCache[imageUrl] = texture;

ブラウザ

コードを書く時に気を使わなくていい
1.chrome mac
chromeを全て閉じて、ターミナルから

open /Applications/Google\ Chrome.app/ --args --disable-web-security --user-data-dir

2.chrome Win
chromeの起動オプションに下記を追加

--disable-web-security --user-data-dir

毎回ターミナル叩くのが面倒な場合
【小ネタ】Chromeのローカルセキュリティポリシーの回避

3.safari
safariを立ち上げて
[開発] -> [クロスオリジンの制限を無効にする]

やっぱりサーバー立てる

syncさせれるし結局これに落ち着いた。
Browsersync入れてみたら便利だった

34
25
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
34
25