CORS filters error in spark rest api and angular front end

1,040 views
Skip to first unread message

kailash adhikari

unread,
Jan 21, 2016, 4:10:21 AM1/21/16
to sparkjava

Having trouble calling my spark rest api from angular front end. request is failing specifically for post request sending some data.

After using the below cors filter still getting the error .

Till now what i have get is that angular app before calling any rest endpoint issues a OPTION request for the resource to check its existece on the server.
 in my case angular is failing a pre flight test for OPTIONS header

is there any way t deal with this in Spark java rest api.


public final class Main{
   
private static final HashMap<String, String> corsHeaders = new HashMap<String, String>();
   
static {
        corsHeaders
.put("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
        corsHeaders
.put("Access-Control-Allow-Origin", "*");
        corsHeaders
.put("Access-Control-Allow-Headers", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,");
        corsHeaders
.put("Access-Control-Allow-Credentials", "true");
   
}
   
public final static void apply() {
       
Filter filter = new Filter() {
           
@Override
           
public void handle(Request request, Response response) throws Exception {
                corsHeaders
.forEach((key, value) -> {
                    response
.header(key, value);
               
});
           
}
       
};
       
Spark.after(filter);
   
}
   
/**
     * Usage
     */

   
public static void main(String[] args){

     
Main.apply();  
     
new ABCController();
     
new XYZController();
   
}
}


Any help will be greatly appriciated.



Jorge Noguera

unread,
Feb 2, 2016, 8:11:12 AM2/2/16
to sparkjava
Hi kailash,

Check your request and response headers, preferably with a Http Client like Postman or Paw (if you're a Mac user).

Also, try using the CORS class as an external class and add it to your controllers insted of the main class.


Mirco

unread,
Feb 2, 2016, 8:42:35 AM2/2/16
to sparkjava
Hi there.

I use the following solution in my main class:

Spark.options("/*", (request, response) -> {

String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
}

String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if (accessControlRequestMethod != null) {
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}
return "OK";
});

Spark.before((request, response) -> {
response.header("Access-Control-Allow-Origin", "*");
});
Reply all
Reply to author
Forward
0 new messages