[英]How to handle HTTP OPTIONS requests in Spring Boot 2 with webflux?
我将 cors 配置如下:
@Bean
WebFluxConfigurer corsConfigurer() {
return new WebFluxConfigurerComposite() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("*");
}
};
}
我的帖子是这样的:
@Bean
RouterFunction<ServerResponse> routes() {
return route(POST("/create")
.and(accept(APPLICATION_JSON))
.and(contentType(APPLICATION_JSON)), serverRequest
-> create(serverRequest);
}
无论如何,在我添加这样的 OPTIONS 路由之前,我的 Angular 应用程序无法发出任何请求:
@Bean
RouterFunction<ServerResponse> routes() {
return route(POST("/create")
.and(accept(APPLICATION_JSON))
.and(contentType(APPLICATION_JSON)), serverRequest
-> create(serverRequest)
.andRoute(OPTIONS("/create"), serverRequest -> ServerResponse.ok().build());
}
那有必要吗? 有什么办法可以删除这个 OPTIONS 处理吗?
我认为 WebFlux 功能端点不支持此功能。 Spring Framework 参考文档改为指向CorsWebFilter
。
您可以定义CorsWebFilter
@Bean
并使用自定义CorsConfiguration
进行配置以实现相同的目的。
OPTIONS 请求是跨域资源共享 (CORS) 中的飞行前请求,它们需要跨不同源发出请求。
某些浏览器发出此预检请求是作为一种安全措施,以确保正在执行的请求得到服务器的信任,服务器理解请求上发送的方法、来源和标头是安全的。
这是过程的工作原理:
您可能还需要公开标题。
@Bean
WebFluxConfigurer corsConfigurer() {
return new WebFluxConfigurerComposite() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("*")
.exposedHeaders("*");
}
};
}
是靠。
如果您的后端和前端构建在同一台服务器上并使用相同的端口,则无需支持 OPTIONS。
如果没有,您必须支持 OPTIONS,因为它用于识别您的服务器上允许使用哪些方法来阻止/允许 CORS(跨源资源共享)。
所有最新的现代浏览器都通过发送 HTTP OPTIONS 进行检查来实现 CORS。 如果您的服务器拒绝或拒绝,浏览器将禁止您的请求。
我在通过“addCorsMappings”添加 CORS 时遇到了同样的问题(就像你一样)似乎上面的配置不支持 OPTIONS 路由。 仅此而已。
@Bean
CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.