Unity3d + WebGL = Cross-Origin Request Blocked

2019-03-31 08:16发布

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...

2条回答
Summer. ? 凉城
2楼-- · 2019-03-31 09:00

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.

查看更多
Ridiculous、
3楼-- · 2019-03-31 09:01

I solve by adding header Access-Control-Allow-Origin:* in response from server. For the explanation, you can figure it out from this link: https://developer.tizen.org/dev-guide/2.2.0/org.tizen.web.appprogramming/html/guide/w3c_guide/sec_guide/cors.htm

Hope this help :)

查看更多
登录 后发表回答