Unity3d + WebGL = Cross-Origin Request Blocked

自古美人都是妖i 提交于 2019-12-20 10:56:09

问题


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


回答1:


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.




回答2:


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 :)



来源:https://stackoverflow.com/questions/30090907/unity3d-webgl-cross-origin-request-blocked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!