播放CORS无效

时间:2017-10-12 10:43:29

标签: playframework playframework-2.6

我已在本地部署了我的Play应用,并通过浏览器中的localhost:9000访问我的REST API,效果非常好。

但是,从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

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

3 个答案:

答案 0 :(得分:3)

您将无法从本地文件中获取CORS。浏览器向服务器发送origin标头值为null,Play不会使用access-control-allow-origin标头进行响应。对于测试,您可以设置本地Web服务器,例如使用

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

然后您可以将文件加载为

http://localhost:8000/index.html

答案 1 :(得分:2)

尝试将其放在application.conf中(它将允许所有来源)

play.filters.cors.allowedOrigins = null

并且不要禁用cors过滤器

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

答案 2 :(得分:1)

因为我花了太多时间在这上面,所以这是Java for Play 2.12的答案:

    在应用程序\ filters \ CorsFilter.java中
  1. package filters;
    
    import java.util.concurrent.CompletionStage;
    import java.util.function.Function;
    
    import com.google.inject.Inject;
    import com.google.inject.Singleton;
    
    import akka.stream.Materializer;
    import play.mvc.Filter;
    import play.mvc.Http.RequestHeader;
    import play.mvc.Result;
    
    
    
    @Singleton
    public class CorsFilter extends Filter {
    
        @Inject
        public CorsFilter(Materializer mat) {
         super(mat);
        }
    
        @Override
        public CompletionStage<Result> apply(Function<RequestHeader, CompletionStage<Result>> next, RequestHeader rh) {
    
         return next.apply(rh).thenApply(result ->
             {
                 return result.withHeaders(
                         "Access-Control-Allow-Origin" , "*",
                         "Access-Control-Allow-Methods" , "OPTIONS, GET, POST, PUT, DELETE, HEAD",
                         "Access-Control-Allow-Headers" , "Accept, Content-Type, Origin, X-Json, X-Prototype-Version, X-Requested-With",
                         "Access-Control-Allow-Credentials" , "true"
                     );
             });
        }
    

    }

  2. 在conf \ application.conf中,在以下位置添加以下行:

    play.filters.enabled += filters.CorsFilter
    
  3. 在您的conf \ routes中,添加以下内容:

    OPTIONS    /          controllers.OptionsController.options(path: String ?= "")
    OPTIONS    /*path     controllers.OptionsController.options(path)
    
  4. 添加类controllers.OptionsController(在app \ controllers \ OptionsController.java中):

    package controllers;
    
    import play.mvc.Controller;
    import play.mvc.Result;
    
    public class OptionsController extends Controller {
    
     public Result options(String path) {
    
         return ok("").withHeaders(
                   "Access-Control-Allow-Origin" , "*",
                   "Access-Control-Allow-Methods" , "GET, POST, PUT, DELETE, OPTIONS",
                   "Access-Control-Allow-Headers" , "Accept, Origin, Content-type, X-Json, X-Prototype-Version, X-Requested-With",
                   "Access-Control-Allow-Credentials" , "true",
                   "Access-Control-Max-Age" , Integer.toString(60 * 60 * 24)
         );
     }
    }