Spring Boot : Enable CORS

mackittipat

Mac

Posted on April 20, 2020

Spring Boot : Enable CORS

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.


Enter fullscreen mode Exit fullscreen mode

CORS Error

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();
    }
}



Enter fullscreen mode Exit fullscreen mode
  • 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");
        }
    };
}
Enter fullscreen mode Exit fullscreen mode

}

Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
mackittipat
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.

Related