I have Spring Boot REST API and React based CMS.
When I send GET ajax requests to the API, they work fine. But when I send POST requests I am stopped by CORS error:
Access to XMLHttpRequest at 'http://localhost:8080/item/add' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am using WebSecurityConfigurerAdapter to configure security.
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
}
I have also tried using annotations instead on my RestControllers, but I had the same issue, GET requests working and POST requests not working. I am still fairly new to Spring Boot, so I am sure there is something I am missing.
@CrossOriginon top of my controllers methods work perfect for me. - Rinat Suleimanov