I am using angular for client and Java as backend service facing the below issue. I went through all available online resources but no luck any help will be appreciated. "Access to XMLHttpRequest at 'http://localhost:8081/demo/customer' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Controller code:
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/demo")
public class CustomerController {
@Autowired
private CustomerService customerService;
@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/customer")
public List<Customer> getCustomerList() {
return customerService.get();
}
}
Configuration Code:
@Configuration
public class CorsConfig {
@Bean
public CORSFilter corsFilter() {
CorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("http://localhost:4200");
config.addAllowedMethod(HttpMethod.DELETE);
config.addAllowedMethod(HttpMethod.GET);
config.addAllowedMethod(HttpMethod.OPTIONS);
config.addAllowedMethod(HttpMethod.PUT);
config.addAllowedMethod(HttpMethod.POST);
((UrlBasedCorsConfigurationSource) source).registerCorsConfiguration("/**", config);
return new CORSFilter(source);
}
}