2017-10-12 76 views
0

我已经部署在本地我的播放应用程序,并从内我的浏览器完美的作品通过访问我的localhost:9000 REST API。播放CORS不工作

不过,我从file:///C:/Users/XXX/XXX//index.html执行jQuery脚本(见下文)时,遇到下列错误:

Failed to load resource: the server responded with a status of 403 (Forbidden) 

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403. 

我跟着https://www.playframework.com/documentation/2.6.x/CorsFilter下的指示。

build.sbt

libraryDependencies ++= Seq(
    jdbc, 
    evolutions, 
    guice, 
    "com.h2database" % "h2" % "1.4.194", 
    javaJpa, 
    "org.hibernate" % "hibernate-core" % "5.2.5.Final", 
    filters 
) 

application.conf

注:我都尝试allowedOrigins = null & allowedOrigins = ["*"]

jQuery的脚本:

$.ajax({ 

    'url' : 'http://localhost:9000/employee/' + user_id + '/weeklyWorkingHours', 
    'type' : 'GET', 
    'success' : function(data) { 
     console.log('Data: '+ JSON.stringify(data)); 

    }, 
    'error' : function(request,error) 
    { 
     console.log("Error: "+JSON.stringify(request)); 
    } 
}); 

这里是戏称:

[warn] p.f.c.CORSFilter - Invalid CORS request;Origin=Some(null);Method=GET;Access-Control-Request-Headers=None 
+0

播放规格说,'在默认情况下所有的起源是allowed'。你提到你尝试了所有的'allowedOrigins = null'&'allowedOrigins = “*”]'。您是否尝试删除它? – Bruno

+0

感谢您的提示。不幸的是,它并没有做到这一点。 – mollwitz

+0

我认为这个问题是在这里'产地=一些(空)'。比赛将验证此为'isValidOrigin =新的URI( “空”)。getScheme NE null'。其中返回false。你可以尝试用有效的“Origin”来完成请求吗?这是'Origin = <一些有效的url>'? – Bruno

回答

2

您将无法获得CORS从本地文件工作。浏览器发送空的origin头值到服务器和播放设备不兼容access-control-allow-origin头回应。为了测试,你可以建立一个本地Web服务器,例如用

cd c:\Users\XXX\XXX 
python -m SimpleHTTPServer 

然后你就可以加载文件

http://localhost:8000/index.html

+0

感谢您的回答。难道没有可能配置Play以这样的方式接受空值吗?我认为CORS仍然没有按预期工作,因为使用CORS的Chrome插件(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi),我可以从本地文件调用localhost 。 – mollwitz

+0

我还没有找到配置Play的方式,我读了足够的源代码,我认为它没有提供。该扩展名不会修改“origin”标题,因此Play不会让您感到快乐。一定要使用开发工具来监视该标题。尝试本地Web服务器。 – cayhorstmann

1

尝试把这个application.conf(它将允许所有来源)

play.filters.cors.allowedOrigins = null 

,并没有禁用CORS过滤

play.filters.enabled += "play.filters.cors.CORSFilter" 
+0

不幸的是,它并没有解决问题。不管怎样,谢谢! – mollwitz

+0

好吧然后play.filters.cors.allowedOrigins = [“http:// localhost:9000”] – cutoffurmind

+0

不工作,因为我正在从不同的域访问我的REST服务 – mollwitz