Created
June 4, 2015 10:29
-
-
Save zikani03/7c82b34fbbc9a6187e9a to your computer and use it in GitHub Desktop.
Simple Cors Filter for Spark Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import spark.Filter; | |
import spark.Request; | |
import spark.Response; | |
import spark.Spark; | |
/** | |
* Really simple helper for enabling CORS in a spark application; | |
*/ | |
public final class CorsFilter { | |
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) { | |
CorsFilter.apply(); // Call this before mapping thy routes | |
Spark.get("/hello", (request, response) -> { | |
return "Hello"; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It works, thanks