LoginSignup
18
16

More than 5 years have passed since last update.

REST APIを実装するときに気をつけるべき CORSの問題 | MDN

Posted at

HTTP access control (CORS) | MDN

XMLHttpRequest オブジェクトにより発行された HTTP リクエストは 同一生成元ポリシー (same-origin policy) の制約を受けます。
→自身が読み込まれたドメインにのみ HTTP リクエストを発行でき、他のドメインには発行できない

Cross-Origin Sharing 標準仕様

クロスサイト HTTP リクエストを可能にするために使用します

ブラウザが HTTP の OPTIONS リクエストを使用してサーバーに対してサポートしているメソッド要求する "プリフライト" を行って、サーバーの "認可" に基づき実際のリクエストを実際の HTTP メソッドにより送信することを認めています。

サーバーは、"クレデンシャル" (Cookie や HTTP 認証データを含む) をリクエストとともに送信するべきかをクライアントに通知することもできます。

サーバーサイドの実装例

Server-Side_Access_Control
https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control

Examples of CORS in Action
http://arunranga.com/examples/access-control/

エラーメッセージ

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
 Origin 'null' is therefore not allowed access.

file://URLから実行している場合
2つの「cross-domain XHR is OK.」というメッセージを伝えるやり方が2つある。

-- One is to send Access-Control-Allow-Origin: *

-- echo back the contents of the Origin header. However, file:// URLs produce a null Origin which can't be authorized via echo-back.

Expressでの対応方法
http://enable-cors.org/server_expressjs.html

18
16
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
18
16