我需要将 CORS 过滤器添加到我的 Spring Boot Web 应用程序中。
我添加了如下文档中所述的 CORS 映射 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html
这是我的配置:
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
// @formatter:off
registry
.addMapping("/**")
.allowedOrigins(CrossOrigin.DEFAULT_ORIGINS)
.allowedHeaders(CrossOrigin.DEFAULT_ALLOWED_HEADERS)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600L);
// @formatter:on
}
...
}
现在,当我尝试访问我的 API 时,我收到以下错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/api/v1.0/user. (Reason: CORS preflight channel did not succeed).
这是FF控制台的截图:
我在做什么错以及如何正确配置 CORS 标头以避免此问题?
原文由 alexanoid 发布,翻译遵循 CC BY-SA 4.0 许可协议
我通过创建一个新的 CORS 过滤器解决了这个问题:
并将其添加到安全配置中:
更新 - 现在我切换到更现代的方式: