Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  }
}
like image 697
Prakash P Avatar asked Jan 05 '23 17:01

Prakash P


1 Answers

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?

like image 170
Prakash P Avatar answered Jan 08 '23 06:01

Prakash P