Search code examples
unity-game-engineparse-platformcors

Unity3d + WebGL = Cross-Origin Request Blocked


I was wondering if anyone could briefly explain how you get the REST api to function with Unity3D project built to WebGL platform. I just started changing my project over today thinking I could use REST to get around Parse's use of threading in a WebGL build I need to make. I promptly ran into the CORS problem though and not being familiar with it, I am unsure how to go about fixing the issue.

Currently I make use of the WWW class to send the request from within Unity.

An Example of "Logging In" a user would be:

        WWWForm form = new WWWForm();

        var headers = form.headers;
        headers["Method"] = "GET";
        headers["X-Parse-Application-Id"] = AppID;
        headers["X-Parse-REST-API-Key"] = RestID;
        headers["X-Parse-Revocable-Session"] = "1";
        headers["Content-Type"] = "application/json";

        WWW www = new WWW("https://api.parse.com/1/login?username="+name+"&password="+password, null, headers);

This works fine in the Editor but after building to WEBGL and uploading to my Host at Parse the following happens...

I receive the following error in FireFox:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.parse.com/1/login?username=jleslie5159&password=Osulator5159!. This can be fixed by moving the resource to the same domain or enabling CORS.

And something similar in Chrome...


Solution

  • For anyone else looking I solved my problem like so:

    WWWForm form = new WWWForm();
            var headers = form.headers;
            headers["X-Parse-Application-Id"] = "AppId";
            headers["X-Parse-REST-API-Key"] = "RestKey";
            headers["Content-Type"] = "application/json";
            WWW www = new WWW("https://api.parse.com/1/login?username="+name+"&password="+password, null, headers);
            while(!www.isDone)
                yield return 1;
    

    The problem stemmed from setting the "headers["Method"] = "GET"" Apparently only certain headers are allowed to be sent or you trigger a CORS violation. I solved the problem by reading the response in the browser console which specified why the request was blocked. And just removed the offending Headers.