如何在play-framework 2.5.x中实现跨源资源共享(CORS)

Pra*_*dey 4 javascript rest playframework angularjs playframework-2.3

我试图通过使用Angularjs-1应用程序从localhost命中Restful URL获取json数据.

我收到了这个错误

http://localhost:9000/mlm/user/all Failed to load resource: 
the server responded with a status of 404 (Not Found)

index.html:1 XMLHttpRequest cannot load http://localhost:9000/mlm/user/all. 

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:63342' is therefore not allowed access. 

The response had HTTP status code 404.
Run Code Online (Sandbox Code Playgroud)

我正在使用play-framework 2.5.4(java).

编辑1:为app.conf添加了CORS设置

    play.filters {
    cors {
    # Filter paths by a whitelist of path prefixes
    pathPrefixes = ["/"]

    # The allowed origins. If null, all origins are allowed.
    allowedOrigins = null

    # The allowed HTTP methods. If null, all methods are allowed
    allowedHttpMethods = ["GET", "POST"]

    allowedHttpHeaders = ["Accept"]
    preflightMaxAge = 3 days
  }
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*dey 7

最后这对我有用.

根据官方文件

Filter.java是(没有工作):

import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import play.http.DefaultHttpFilters;

import javax.inject.Inject;

public class Filters extends DefaultHttpFilters {
    @Inject public Filters(CORSFilter corsFilter) {
        super(corsFilter);
    }
}
Run Code Online (Sandbox Code Playgroud)

但它有效.有效的是:

Filter.java(工作)

import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import play.http.HttpFilters;
import javax.inject.Inject;

public class Filters implements HttpFilters {

    @Inject
    CORSFilter corsFilter;

    public EssentialFilter[] filters() {
        return new EssentialFilter[] { corsFilter.asJava() };
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢这个答案,关于堆栈溢出的类似问题.

但是为什么2.5.x 的官方文档的Filter.java代码不起作用的原因是百万美元的问题?