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

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

java - Trouble-shooting CORS in Play Framework 2.4.x

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...