Spring Boot : Enable CORS
Mac
Posted on April 20, 2020
If you have client app running on http://localhost:4200
and it make a request to API written in Spring Boot that is running on http://localhost:8080
, You should get the below error because client app and API has a different origin (domain, protocol or port).
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.
- At Class or Method level
@RestController
public class MainController {
@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/hello")
public User hello() throws Exception {
return User.builder().name("Mac").build();
}
}
- Global ```java
@Configuration
public class WebConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:4200");
}
};
}
}
π πͺ π
π©
Mac
Posted on April 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.