我面临的问题是:我已为foodomain.com
启用了CORS设置,但服务器允许所有域访问RESTapi。
服务器在Spark Java Framework中的嵌入式Jetty服务器上启动。此Jetty服务器在Ubuntu Linux服务器上启动,并侦听端口4567.
以下代码段显示了CORS设置:
private static void enableCORS() {
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";
});
before((request, response) -> {
response.header("Access-Control-Request-Method", "POST, GET, OPTIONS, DELETE, PUT");
response.header("Access-Control-Allow-Origin", "https://clientfoodomain.com");
response.header("Access-Control-Allow-Headers", "Authorization,Access-Control-Expose-Headers,Access-Control-Allow-Headers,Origin,Accept,X-Requested-With,content-type,Access-Control-Request-Method,Access-Control-Request-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Credentials,user_language,");
response.header("Access-Control-Allow-Credentials", "true");
response.header("Vary", "Origin");
response.type("application/json");
});
}
如果我通过Postman访问Api,它不应该将响应暴露给前端,并且应该在控制台中暴露CORS
失败,但它会公开响应并显示Access-Control-Allow-Origin-Header
。
上面的代码片段来自Java Spark文档:http://sparkjava.com/tutorials/cors