Trouble-shooting CORS in Play Framework 2.4.x

前端 未结 7 689
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 14:55

I have a java play framework 2.4.x web app providing a JSON/HTTP API. When I run my front-end HTML/JS file:///Users/nize/tmp/index.html calling the API on

7条回答
  •  北海茫月
    2020-12-10 15:45

    First add/edit these lines(configurations) into your conf/application.conf

     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
     }   
    

    (Note that lines starting with '#' are commented lines.)

    Then go to build.sbt and add this line.

    libraryDependencies += filters
    

    Finally make a Java Class named 'Filters.java' and include this to the root directory(/app).

    import play.api.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 };
        }
    }
    

    You can refer official documentation for more information.

提交回复
热议问题