-
-
Save MaxenceG2M/2eb6541e29ac0d075338b884e8873b6d 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