Today, I, who mainly used server-side rendering for development with a colleague at the company, did not know much about cors. Therefore, I implemented the project for the first time excluding cors settings, but a colleague asked me to handle cors errors, and I did not know much about cors, so I wrote this post.
Error: CORS is an error that occurs because other addresses try to use my home address, preventing resource sharing.
Solution: There are several ways to set cors in Spring Boot. In the config part where I set security
//When connecting to the front end, allow CORS.
http.cors().configurationSource(request -> {
var cors = new CorsConfiguration();
// Enter the addresses to allow CORS in the form of a list below.
cors.setAllowedOrigins(List.of("http://localhost:3000"));
cors.setAllowedMethods(List.of("*"));
cors.setAllowedHeaders(List.of("*"));
cors. setAllowCredentials(true);
cors.addExposedHeader("Authorization");
return cors;
Put it in and it worked.
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(),
HttpMethod.DELETE.name(), HttpMethod.OPTIONS.name())
.allowedHeaders("*")
.exposedHeaders("Authorization")
.allowCredentials(true);
}