简体   繁体   中英

How to impliment Cross-Origin Resource Sharing ( CORS ) in play-framework 2.5.x

I am trying to get json data by hitting a Restful URL from localhost using Angularjs-1 application.

I am getting this error

http://localhost:9000/mlm/user/all Failed to load resource: 
the server responded with a status of 404 (Not Found)

index.html:1 XMLHttpRequest cannot load http://localhost:9000/mlm/user/all. 

Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

Origin 'http://localhost:63342' is therefore not allowed access. 

The response had HTTP status code 404.

I am using play-framework 2.5.4 (java).

Edit 1 : Added CORS settings to app.conf

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

    # The allowed origins. If null, all origins are allowed.
    allowedOrigins = null

    # The allowed HTTP methods. If null, all methods are allowed
    allowedHttpMethods = ["GET", "POST"]

    allowedHttpHeaders = ["Accept"]
    preflightMaxAge = 3 days
  }
}

Finally this worked for me .

According to official docs

Filter.java is ( didn't worked ) :

import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import play.http.DefaultHttpFilters;

import javax.inject.Inject;

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

But it dint worked. What worked is :

Filter.java( worked )

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

thanks to this answer ,similar question on stack-overflow.

But why the Filter.java code of official docs for 2.5.x is not working is question of million dollar?

Seems like it's a bug in the framework with the cast to DefaultHttpFilters.java https://github.com/playframework/playframework/pull/6238

Make sure you follow this guide: https://www.playframework.com/documentation/2.5.x/CorsFilter

But don't use the default implementation of DefaultHttpFilters instead, use the following:

package filters;
import play.http.*;

import java.util.Arrays;

import play.mvc.EssentialFilter;

/**
 * Helper class which has a varargs constructor taking the filters. Reduces boilerplate for defining HttpFilters.
 */
public class MyDefaultHttpFilters implements HttpFilters {

  private final EssentialFilter[] filters;

  public MyDefaultHttpFilters(play.api.mvc.EssentialFilter... filters) {
    this.filters = Arrays.stream(filters).map(f -> f.asJava()).toArray(EssentialFilter[]::new);
  }

  @Override
  public EssentialFilter[] filters() {
    return filters;
  }
}

Your Filter class will then have to look like this:

import javax.inject.*;
import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import filters.MyDefaultHttpFilters;

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

I think you have to put a CORS allow header in your server:

response.setHeader("Access-Control-Allow-Origin", "*");//cross domain request/CORS

Don't know the framework you are using, but somewhere you should have access to the response object and then write something like this.

Additionally, most clients do a http OPTIONS request before the actual request is made, to check for supported options and access to the server. You don't have to process the full request if you see that the http method is OPTIONS. Just write out the headers and close the socket / connection.

It's very documented .

The filter can be configured from application.conf . For example:

play.filters.cors {
  pathPrefixes = ["/some/path", ...]
  allowedOrigins = ["http://www.example.com", ...]
  allowedHttpMethods = ["GET", "POST"]
  allowedHttpHeaders = ["Accept"]
  preflightMaxAge = 3 days
}



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

    # The allowed origins. If null, all origins are allowed.
    allowedOrigins = null

    # The allowed HTTP methods. If null, all methods are allowed
    allowedHttpMethods = ["GET", "POST", "OPTIONS"]

    preflightMaxAge = 3 days
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM