简体   繁体   中英

'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

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

Try this:

 @Bean
public CorsConfigurationSource corsConfigurationSource() {
    String localURI = "http://localhost:4200";

    List<String> allowedOrigins = List.of(localURI);
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(allowedOrigins);
    configuration.setAllowedMethods(java.util.List.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
    // setAllowCredentials(true) is important, otherwise:
    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
    configuration.setAllowCredentials(true);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(java.util.List.of("Authorization", "Cache-Control", "Content-Type", "Access-Control-Allow-Origin"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM