I'm developing an Angular 2 application on top of a Play Framework 2.5 (Java) back-end. If I access my endpoints through browser URL, they work fine. However, calling it from the Angular 2 application shows the error:
XMLHttpRequest cannot load localhost:9000/app/myendpoint. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:3000' is therefore not allowed access. The response had HTTP status code 500.
I have tryed to follow the documentation and create the filter:
In application.conf:
play.filters {
cors {
pathPrefixes = ["/app"]
allowedOrigins = null
allowedHttpMethods = null
}
Filter:
import play.mvc.*;
import play.api.http.DefaultHttpFilters; <- error with this import
import play.filters.cors.CORSFilter;
public class Filters extends DefaultHttpFilters {
@Inject public Filters(CORSFilter corsFilter) {
super(corsFilter);
}
}
In build.sbt:
libraryDependencies ++= Seq(
...,
filters
)
Does anyone knows the true solution? Thank you :)
Working code:
Filters.java (on project's root)
import com.google.inject.Inject;
import com.google.inject.Singleton;
import play.http.HttpFilters;
import play.mvc.EssentialAction;
import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
@Singleton
public class Filters 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;
}
}
In application.conf:
#filters += Filters <- yes, it is commented since my Filters is in project's root
libraryDependencies += filters
play.filters {
cors{
# allow all paths
pathPrefixes = ["/"]
# allow all origins
allowedOrigins = null
allowedHttpMethods = ["GET", "POST", "PUT", "DELETE"]
# allow all headers
allowedHttpHeaders = null
} ...
In build.sbt:
libraryDependencies ++= Seq(
...,
filters
)
Thank you all! :)
withCredentials
the exact origin must be provided instead of just*
. CORS only applies if the HTTP request is made to a different URL then whereindex.html
was originally loaded, this is why it works if you enter the URL in the browser directly.cors
config and the request headers/info from the browser? my guess would be that this is just an issue with configuration. for example, if you follow the the docs, you might setallowedHttpHeaders = ["Accept"]
, but angular might be sending other headers. an easy way to check if it is misconfiguration is to change yourcors
config to just containanyOriginAllowed = true
and nothing else.