Is Cross-Origin Resource Sharing (CORS) AJAX Requests interfering with your development ?

This is again another learning from one of my latest projects. I have been creating a Backbone based web application. The data was being fetched from the webservice exposed on the developers machine. The issue occurred when backbone view tried making AJAX call to the webservice; it was being rejected by Chrome browser marking it as a CORS call.

We wanted an immediate intermediary solution to continue with our development and we found that using a command line parameter  while starting chrome browser makes it ignore CORS check during AJAX call.

I thought it would come handy to someone facing same issue and needing immediate solution :-)

Please use the below steps to start chrome browser with CORS security disabled;

1. press windows button + R key to start windows Run prompt
2. type follwoing command i.e.

chrome.exe --disable-web-security

EDIT:
Some people could not get CORS working using above method.

For them, here is a little PHP function that can also help you get rid of CORS issue.
All you need to do is call this function in the start of the PHP page.


/**
 *  An example CORS-compliant method.  It will allow any GET, POST, or OPTIONS requests from any
 *  origin.
 *
 *  In a production environment, you probably want to be more restrictive, but this gives you
 *  the general idea of what is involved.  For the nitty-gritty low-down, read:
 *
 *  - https://developer.mozilla.org/en/HTTP_access_control
 *  - http://www.w3.org/TR/cors/
 *
 */
function cors() {
    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");        
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
        exit(0);
    }
    echo "You have CORS!";
}

Thanks for reading and happy coding :-)

0 comments:

Post a Comment