How to allow cross-origin ajax request get and set cookie


How to allow cross-origin ajax request get and set cookie?

Step 1: send header Access-Control-Allow-Credentials: true

Example for PHP:

header ("Access-Control-Allow-Credentials: true");  

Step 2: set header Access-Control-Allow-Origin: http://yourdomain.com

Example for PHP

header ("Access-Control-Allow-Origin: ".$_SERVER['HTTP_ORIGIN']);

Note: you don’t use:

Access-Control-Allow-Origin: *

Step 3: Add the following to your ajax request (apply for jQuery).

xhrFields: { withCredentials:true }

Example:

$.ajax({
    type: 'GET',
    url: 'http://yourdomain.com/ajax.php?action=session',
    headers: {
        'Authorization': 'Bearer ' + BearerToken
    },
    dataType: 'JSON',
    xhrFields: {
       withCredentials: true
    },
    success: function (d) {
                 
    }
});

Leave a Reply