嗨,我无法在我的项目中禁用CORS。我将自定义过滤器和Spring Security Config用于CORS配置。我已经看到了一个很好的答案:Can you completely disable CORS support in Spring?
但是当我尝试了以下实现时,仍然会收到CORS错误:
CORS配置:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class CorsFilter @Autowired
constructor() : CorsFilter(configSrc()) {
companion object {
private fun configSrc(): UrlBasedCorsConfigurationSource {
val config = CorsConfiguration()
config.allowCredentials = true
config.addAllowedOrigin("http://127.0.0.1:3000")
config.addAllowedHeader("*")
config.addAllowedMethod("*")
val src = UrlBasedCorsConfigurationSource()
src.registerCorsConfiguration("/**", config)
return src
}
}
}Ive还尝试将允许的原点设置为如下所示,但没有结果:
config.addAllowedOrigin("http://127.0.0.1:3000")
这些是来自进行中的OPTIONS请求的Response header :这是我得到的确切错误:
您能否指出任何其他想法,或者为什么会这样呢?我认为这将是一个易于解决的问题,但最终却浪费了我很多时间。
谢谢
最佳答案
您可以尝试通过以下方式在应用程序类中添加CORS映射:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/v1/**")
.allowedHeaders("*")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true)
.maxAge(3600);
}
};
}
https://spring.io/guides/gs/rest-service-cors/
关于java - CORS和错误以及Access-Control-Allow-Origin header 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63884056/