Unity3d + WebGL = 跨域请求被阻止 [英] Unity3d + WebGL = Cross-Origin Request Blocked
问题描述
我想知道是否有人可以简要解释一下如何让 REST api 与构建到 WebGL 平台的 Unity3D 项目一起运行.我今天刚开始改变我的项目,认为我可以使用 REST 来解决 Parse 在我需要制作的 WebGL 构建中使用线程的问题.我很快就遇到了 CORS 问题并且不熟悉它,我不确定如何解决这个问题.
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.
目前我使用 WWW 类从 Unity 内部发送请求.
Currently I make use of the WWW class to send the request from within Unity.
用户登录"的示例是:
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);
这在编辑器中运行良好,但在构建到 WEBGL 并上传到我的主机在 Parse 后,会发生以下情况...
This works fine in the Editor but after building to WEBGL and uploading to my Host at Parse the following happens...
我在 FireFox 中收到以下错误:
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.
Chrome 中类似的东西...
And something similar in Chrome...
推荐答案
对于正在寻找的其他人,我像这样解决了我的问题:
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;
问题源于设置 "headers["Method"] = "GET"" 显然只允许发送某些标头或触发 CORS 违规.我通过阅读浏览器控制台中的响应解决了这个问题,该响应指定了请求被阻止的原因.并删除了有问题的标题.
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.
这篇关于Unity3d + WebGL = 跨域请求被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!