LoginSignup
26
27

More than 5 years have passed since last update.

XHR2でクロスドメイン通信する際のサーバ側の設定

Last updated at Posted at 2013-02-26

APIなどを提供しているサーバサイドにいくつかHeaderの設定が必要。
かつ、JSでのリクエストも少しHeaderをいじる必要がある。

サーバサイド

Apache

Header append Access-Control-Allow-Origin *
Header append Access-Control-Allow-Headers Content-Type

nginx

setting.conf
location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Headers' 'Content-Type,Accept';
        add_header 'Access-Control-Allow-Method' 'GET, POST, OPTIONS, PUT, DELETE';
}

クライアントサイド

JavaScript

モダンブラウザであれば、特に意識することなく通信できる。

XHR.js
var xhr = new XMLHttpRequest();

xhr.open('POST', 'http://hoge.com/', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xhr.send('hoge=fuga');

for IE8

IE8はクロスドメイン通信用にXMLHttpRequestの代わりにXDomainRequestというオブジェクトを用意しているので、そちらを使う必要がある。

ただ、jQueryなどのライブラリを使っている場合は若干分岐がめんどくさいので、下記の記事を参考にラッパーオブジェクトを作り、さらにjQuery.ajaxで使われるように設定してやるといい。

参考: IE8+jQueryによるクロスドメイン通信とXDomainRequestラッパーの作成

XHR.js
if( window.XDomainRequest ){
    var xdr = new XDomainRequest();
    xdr.onerror = function(){
        alert( "error" );
    }
    xdr.onload = function(){
        alert( xdr.contentType + "\n" + xdr.responseText );
    }
    xdr.open( "get", "http://remote.example.com/data.txt" );
    xdr.send( null );
}
26
27
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
26
27