«http://localhost: 4200» заблокировано политикой CORS: на запрошенном ресурсе отсутствует заголовок «Access-Control-Allow-Origin» - PullRequest
0 голосов
/ 06 августа 2020

Я использую angular для клиента и Java как серверную службу, столкнувшись с проблемой, указанной ниже. Я просмотрел все доступные онлайн-ресурсы, но безуспешно, любая помощь будет оценена по достоинству. «Доступ к XMLHttpRequest по адресу 'http://localhost: 8081 / demo / customer' from origin 'http://localhost: 4200' заблокирован политикой CORS: заголовок« Access-Control-Allow-Origin »отсутствует в запрашиваемый ресурс.

Код контроллера:

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

1 Ответ

0 голосов
/ 06 августа 2020

Попробуйте следующее:

 @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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...