CORS クロスドメインを利用(自分用メモ)
環境:AWS EC2
OS:UBUNTU
サーバー:Apache2.4
やりたかった事
1:www.hogehoge.comとwww.fugafuga.com間でAjaxを利用しデータをやり取りしたい。
普通にやると
1:www.hogehoge.comから
$.ajax({
url: "https://www.fugafuga.com",
method: "POST",
dataType: "json",
withCredentials: true,
crossOrigin: true,
data: JSON.stringify(postList),
processData: false,
contentType:"application/json; charset=utf-8",
})
2:エラーゲット
XMLHttpRequest cannot load http://www.fugafuga.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://hogehoge.com' is therefore not allowed access.
3:どういう問題か?
CORSヘッダとは?
Cross-origin resource sharing (CORS)はWebサーバがドメインをまたいでリソースを配信するために、
W3Cによって勧告されたアクセス制御の仕組みです。リソースを提供するサーバが、どのサーバに対して自身のリソース利用を許可するかを示すHTTP ヘッダを追加することによって動作します。この仕組みの中で定義されたHTTPヘッダの事をCORSヘッダと呼びます。
4:ならばHeaderを追加
サーバー側に以下のheaderを付与。私の場合はApacheなので、
以下を追加。
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
5:これで、、、、できない、、、なんでやねん。
OPTIONS http://fugafuga.com 405 (Method Not Allowed)
どうやら、JSONでPOSTしているのでOPTION扱いになり、preflightで弾かれておるようです。
その場合は、以下をApacheに追加。GETとかなら大丈夫だった。
このコマンドを有効にするにはmod_rewriteを有効にしておく必要あり。REQUESTが OPTIONだったら200を返すように指示。
参考:http://oxynotes.com/?p=7392
<Directory /var/www/>
RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=200,L]
</ Directory>
これでめでたしめでたし。