Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 http://localhost:9000 chrome shows

XMLHttpRequest cannot load http://localhost:9000. 
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.

I have configured the web app as per the instructions given in Play Framework 2.4.x CORS Documentation:

  • Update to build.sbt
  • Added the class Filters.javato the root of the project (also tried /app)
  • Added the following stanza to the application.conf:
    play.filters.cors {
      allowedOrigins = ["*","http://localhost"]
      #allowedHttpMethods = ["GET", "POST"]
      #allowedHttpHeaders = ["Accept"]
      #preflightMaxAge = 3 days
    }
    

What am I missing?

Edit: The symptoms look identical or similar to Other very similar stackoverflow post. That problem was solved by reconfiguring Cisco AnyConnect VPN which was installed on the computer. I, however, don't have that software installed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
377 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...