LoginSignup
28
16

More than 3 years have passed since last update.

クロスドメインで'X-Requested-With'の設定

Last updated at Posted at 2018-07-27

クロスドメインでAjax通信をする

クロスドメインでapi通信を行う際、
Access-Control-Allow-Originなどの許可が必要になり、これはapi側に実装します。

さらに、Cookieを扱いたい場合は、withCredentialsの設定も必要になり、api側で許可し、さらにクライアント側でも設定を送信しないとCookieを扱うことができません。

また、クロスドメインの場合、headerに'X-Requested-With' : 'XMLHttpRequest'を入れて送信しなければ、api側でAjaxであることが伝わらないとのことだったので

headers: {'X-Requested-With': 'XMLHttpRequest'}

をajaxで送信しましたが、

Failed to load https://test.com/api/sendData: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://test.com' is therefore not allowed access. The response had HTTP status code 400.

というエラーが出るしAjax判定もされず…。
たぶん、withCredentialsの設定もしているからかなと思って同じところに設定を書いたらうまくいきました。

$(document).ready(function() {
    var post_data = {};
    $.ajax({
    type : 'POST',
    url : 'https://test.com/api/sendData',
    data : {
        'post_data' : post_data
        },
    xhrFields: {
        withCredentials: true,
        X-Requested-With : 'XMLHttpRequest'
                },
    // 通信成功時処理
    success : function(result) {
        },
    // 通信失敗時処理
    error : function(result) {
        }
    });
});

これで、送信の形式がOPTIONからPOSTになり、Ajaxで送信している判定もされた。

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