Home > Enterprise >  How deactivate CORS in a Spring Boot API (Version 2.2.6)
How deactivate CORS in a Spring Boot API (Version 2.2.6)

Time:11-19

I am currently working on a React Front-End with an already existing Spring Boot Backend.

When developing locally i ran into the typicall CORS Error:

Access to fetch at 'http://localhost:8180/api/data/firms' from
origin 'https://localhost:8087' 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.

runtime.js:98 GET http://localhost:8180/api/data/firms net::ERR_FAILED

I already tried most of the solutions mentioned in this post however nothing really helped. By adding one of these snippets

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
    }
@Bean
  public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
  }

or creating a CorsFilter the CORS Error was gone but now the API always returned a HTTP 500 Error.

Does anyone know a solution for my problem?

CodePudding user response:

You can add this in your controller class.

@CrossOrigin(origins = "${cross.origin}")
@RestController

application.properties

cross.origin=https://localhost:8087

CodePudding user response:

I've added new answer for Spring Boot.

Additionally, if you are using create-react-app, you will avoid CORS problem to set up proxy. (In this case, it is not required to change Spring Boot settings.)

package.json:

  "proxy": "http://localhost:8180",
  • Related