我已经在本地部署了我的 Play 应用程序,并通过localhost:9000
我的浏览器访问我的 REST API 工作正常。
但是,从以下位置执行 jQuery 脚本(见下文)时出现以下错误file:///C:/Users/XXX/XXX//index.html
:
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
:
play.filters.enabled += "play.filters.cors.CORSFilter"
play.filters.cors {
# allow all paths
pathPrefixes = ["/"]
# allow all origins (You can specify if you want)
allowedOrigins = null
allowedHttpMethods = ["GET", "POST", "PUT", "DELETE"]
# allow all headers
allowedHttpHeaders = null
}
注意:我尝试了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));
}
});
以下是 Play 所说的:
[warn] p.f.c.CORSFilter - Invalid CORS request;Origin=Some(null);Method=GET;Access-Control-Request-Headers=None