【发布时间】:2019-12-26 00:33:24
【问题描述】:
我有 Spring Boot REST API 和基于 React 的 CMS。
当我向 API 发送 GET ajax 请求时,它们工作正常。但是当我发送 POST 请求时,我被 CORS 错误阻止:
从源“http://localhost:3000”访问“http://localhost:8080/item/add”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问控制允许源” ' 请求的资源上存在标头。
我正在使用 WebSecurityConfigurerAdapter 来配置安全性。
BasicWebSecurityConfigurerAdapter.kt
override fun configure(http: HttpSecurity?) {
http?.csrf()?.disable()
http?.cors()
http?.authorizeRequests()
?.anyRequest()?.authenticated()
?.and()
?.httpBasic()
}
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val configuration = CorsConfiguration()
configuration.allowedOrigins = mutableListOf("http://localhost:3000")
configuration.allowedMethods = mutableListOf("GET", "POST")
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", configuration)
return source
}
我也尝试在我的 RestControllers 上使用注释,但我遇到了同样的问题,GET 请求有效而 POST 请求无效。 我对 Spring Boot 还很陌生,所以我确信我缺少一些东西。
【问题讨论】:
-
我的控制器方法顶部的
@CrossOrigin等注释非常适合我。 -
正如我在问题中所写,我使用它们得到了相同的结果。在尝试使用 WebSecurityConfigurerAdapter 之前,我先尝试了注释。
-
以防万一,你用的是什么spring boot版本?我正在使用 2.1.4.RELEASE。您还可以提供更多代码吗?将尝试在本地复制它。
-
Spring Boot 是 2.1.6.RELEASE,我会用更多代码更新问题。
-
谢谢 :) 当我要更新问题时,我重新阅读了代码并能够找到错误,它完全在其他地方。
标签: spring spring-boot kotlin spring-security