Home > Back-end >  How do I configure CORS globally in Spring Boot?
How do I configure CORS globally in Spring Boot?

Time:07-13

I am trying to configure CORS globally in Spring using the following code:

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowCredentials(false);
    }
}

However, I am being blocked when I make a call from http://localhost:3000

Message:

'Access to fetch at 'http://localhost:8081/api/assignments' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.'

Any suggestion would be great. Thanks.

CodePudding user response:

This is what resolved my CORS issue:

@Configuration
public class WebMvcConfig
{
    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:3000");
            }
        };
    }
}

CodePudding user response:

try adding following line to the method:

.allowedOrigins("http://localhost:3000")
  • Related