LoginSignup
3

More than 5 years have passed since last update.

CORS (UBUNTU+APACHE on EC2)クロスドメインで困った事

Last updated at Posted at 2017-06-29

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ヘッダと呼びます。

参照:https://community.akamai.com/groups/akamai-japan/blog/2016/07/05/cors%E3%83%98%E3%83%83%E3%83%80%E3%81%AE%E8%A8%AD%E5%AE%9A%E6%96%B9%E6%B3%95%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6

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>

これでめでたしめでたし。

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
3