Enabling the CORS filter for Lagom Java

2019-08-04 15:02发布

问题:

I have followed the instruction of Cross-Origin Resource Sharing in order to access localhost:9000 (Lagom GateWay where my microservices are running) from localhost:3000 (where my angular front-end is running). but still I face:

XMLHttpRequest cannot load http://localhost:9000/api/myservice. No 'Access-Control-Allow-Origin' header is present on the requested resource 

doe anyone have a sample or project that enabling CORS works there?

回答1:

This is a quote from James Roper He publish in the Lagom google user group

The simplest way to get CORS working in Lagom is to use Play's CORS support (Lagom is built on top of Play):

https://www.playframework.com/documentation/2.5.x/CorsFilter



回答2:

Add a Filters class which extends the Play class

public class Filters extends DefaultHttpFilters {

  @Inject
  public Filters(CORSFilter corsFilter) {
    super(corsFilter);
  }
}

and add conf to include that filter

play.http.filters = "io.my.http.Filters"

you may also need to configure the filter

play.filters.cors {
  allowedOrigins = null
}


回答3:

For the sake of others working with Angular 4 front-end and lagom backend project. I have managed to solve this way.

*I added this line below in my build.sbt in both api and impl *

libraryDependencies += filters

In my impl directory, i created folder filters and added the code below

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()};
    }
}

In my application.conf i added the code that follows

play.filters.hosts {
  # Allow requests to example.com, its subdomains, and localhost:9000.
  allowed = ["localhost:5000", "localhost:9000"]
}

play.http.filters = "filters.Filters"

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

  # The allowed origins. If null, all origins are allowed.
  allowedOrigins = null
  allowedHttpMethods = ["GET", "POST"]
  allowedHttpHeaders = ["Accept"]
  preflightMaxAge = 3 days
}

After this, i restarted my lagom microservices and it worked like a charm.