在 Java play 应用中启用 CORS 过滤器

Enabling CORS filter in Java play app

我试图在我的 java 播放应用程序上启用 CORS 过滤器。我正在使用 angularjs 访问本地主机以获取一些数据。这是我在 play app 方面所做的,

application.conf

play.http.filters = "com.de.filters.Filters"
play.filters.cors {
    allowedOrigins = null
    allowedHttpMethods = ["GET", "POST"]
    allowedHttpHeaders = ["Accept"]
    preflightMaxAge = 3 days
}

Filters.java

public class Filters implements HttpFilters {
    @Inject
    CORSFilter corsFilter;

    public EssentialFilter[] filters() {
        return new EssentialFilter[]{corsFilter};
    }
}

当我尝试调用我的服务时,出现错误,

XMLHttpRequest cannot load http://localhost:9000/app/search/0/10. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 403.

我该如何解决这个问题?

来自Play 2.3 Documentation, 首先将您的过滤器添加到 build.sbt 中的 libraryDependencies 列表,如下所述。

libraryDependencies += filters

那么,在application.conf中,不要将play.filters.cors.allowedOrigins设为[null],默认为"all origins are allowed"。设置有效的域列表或忽略它。不要忘记引用您的过滤器:

play.http.filters = "filters.Filters"

最后,在您的 Filters.filter() 方法中,如下所示,指定 asJava() 方法,如文档中所述。

public EssentialFilter[] filters() {
    return new EssentialFilter[] { 
        corsFilter.asJava()
    };
}

改为将这些行添加到 application.conf。

play.filters.cors {
  # allow all paths
  pathPrefixes = ["/"]
  # allow all origins
  allowedOrigins = null
  allowedHttpMethods = ["GET", "POST", "PUT", "DELETE"]
  # allow all headers
  allowedHttpHeaders = null
}

你可以参考我的this回答了解更多信息。

我终于让我的 CORSFilter 开始工作了。关于此的文档很少,而且那里的文档不起作用。希望这可以帮助某人。 (播放2.5.4)

import com.google.inject.Inject;
import play.http.HttpFilters;
import play.mvc.EssentialAction;
import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;

public class MyFilters extends EssentialFilter implements HttpFilters {

    @Inject
    private CORSFilter corsFilter;


    @Override
    public EssentialAction apply(EssentialAction next) {
        return corsFilter.asJava().apply(next);
    }

    @Override
    public EssentialFilter[] filters() {
        EssentialFilter[] result = new EssentialFilter[1];
        result[0] = this;

        return result;
    }
}

也将此添加到 application.conf

play.filters.cors{
# allow all paths
  pathPrefixes = ["/"]
  # allow all origins
  allowedOrigins = null
  allowedHttpMethods = ["GET", "POST", "PUT", "DELETE"]
  # allow all headers
  allowedHttpHeaders = null
}