springboot CORS policy

javaspringboot

In a Spring Boot application, you can enable CORS (Cross-Origin Resource Sharing) by adding the @CrossOrigin annotation to your controller or by adding the following configuration to your application class:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

This will allow CORS for all paths and all HTTP methods. If you want to allow CORS for only specific paths or methods, you can specify them in the addMapping method:

registry.addMapping("/api/**")
        .allowedOrigins("http://localhost:3000")
        .allowedMethods("GET", "POST");

This will allow CORS for all paths that start with “/api/”, with only the “GET” and “POST” methods, and only for requests from the ”http://localhost:3000” origin.

You can also set other CORS options, such as allowed headers and exposed headers, using the methods of the CorsRegistration object returned by the addMapping method.