我为基本api配置了java spark api。当我从Postman调用URL(带有基本身份验证)时,它返回JSON。但是,当我从Angular 4应用程序调用相同的URL时,它返回:预检的响应具有无效的HTTP状态代码401。 角度中的标题已正确设置,我已经阅读了这个答案: Angular 2 - Response for preflight has invalid HTTP status code 401
我知道API存在问题,但我不知道如何配置它以在auth之前允许来自浏览器的OPTIONS。路线创建代码在下面的代码中
private static void create_routes() {
staticFileLocation("/static");
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", "*");
});
RouteOverview.enableRouteOverview("/debug");
path("/api", () -> {
before("/*", new SecurityFilter(authConfig, "DirectBasicAuthClient"));
});
after("/api/*", (request, response) -> response.type("application/json"));
new ApiController();
}
答案 0 :(得分:0)
您必须将OPTION添加为请求方法:
Spark.before((request, response) -> {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Request-Method", "GET,POST,PUT,DELETE,OPTIONS");
});