我为基本 API 配置了 Java Spark api。当我从邮递员调用 URL(带有基本身份验证(时,它会返回 JSON。但是当我从 Angular 4 应用程序调用相同的 URL 时,它会返回:预检响应具有无效的 HTTP 状态代码 401。角度中的标题设置正确,我已经阅读了这个答案:角度 2 - 预检响应具有无效的 HTTP 状态代码 401
而且我知道问题出在 API 中,但我不知道如何配置它以在身份验证之前允许来自浏览器的选项。 路由创建代码在下面的代码中
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();
}
您必须添加 OPTION 作为请求方法:
Spark.before((request, response) -> {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Request-Method", "GET,POST,PUT,DELETE,OPTIONS");
});