问题
I'm creating a web fronted written using jQuery which sends REST request to a REST Web Service written in Java using Spring framework. I'm facing a weird error with CORS requests. In particular, everything works fine if I use Safari; instead, with Chrome all DELETE requests fail (both GET and POST requests work fine in Chrome too).
The error I'm getting is:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
The response had HTTP status code 403.
This happens when a first OPTIONS request is issued by Chrome.
My code regarding CORS is:
@Configuration
@EnableWebMvc
public class CorsConfigurator extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS");
}
}
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new CorsConfigurator();
}
}
I also tried to add the @CrossOrigin
annotations to my @RestController
but nothing changed. Does somebody know ho to fix this?
Thank you, Marco
回答1:
I just added @CrossOrigin
to the method in controller and that fixed my problem
回答2:
I got this error in spring boot application and I resolved it by adding or enabling cors features as below
cors: allowed-origins: "http://localhost:8082" allowed-methods: "" allowed-headers: "" exposed-headers: "Authorization,Link,X-Total-Count" allow-credentials: true max-age: 1800
来源:https://stackoverflow.com/questions/39307591/java-spring-rest-api-cors-not-working-for-delete-requests-via-jquery-with-chrome