2017-10-12 74 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