I using Spring Boot API RESTful that get up automatically by your Entities Class. I'm consuming this apiRest from a front-end web app but it gives me this error:
No 'Access-Control-Allow-Origin' header is present on the requested resource
I'm setting the CORS configuration using the applicantion.properties specified here.
My basic configuration is:
endpoints.cors.allow-credentials=true
endpoints.cors.allowed-origins=*
endpoints.cors.allowed-methods=*
endpoints.cors.allowed-headers=*
I have tried different combinations in those variables but still not working. Any ideas?
Enable CORS in Controller Method We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.
Controller Method CORS ConfigurationBy default, its allows all origins, all headers, and the HTTP methods specified in the @RequestMapping annotation.
Access to XMLHttpRequest at 'http://localhost:8080/hello' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. You can resolve this problem by enable CORS in Spring Boot.
This is not very clear in the official Spring documentation, and it is very easy to be misled by the official Spring Boot documentation.
The truth is that you CANNOT set the global CORS congfiguration using the application.properties file. You HAVE TO use JavaConfig as described by the Cors chapter from Spring Framework Documentation.
Just use the @EnableWebMvc
annotation on a @Configuration
class that implements WebMvcConfigurer
and overrides the addCorsMappings
method as follows:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
}
I got the answer by myself:
Just add this to application.java
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
}
};
}
Spring boot properties prefixed by endpoints.cors.* are used by Actuator so that's why it will not work with MVC endpoints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With