“ http:// localhost:4200”已被CORS策略阻止:所请求的资源上没有“ Access-Control-Allow-Origin”标头

时间:2020-08-06 06:02:25

标签: java angular web-services

我正在将angular用于客户端和Java作为后端服务,面临以下问题。我浏览了所有可用的在线资源,但没有任何帮助将不胜感激。 “ CORS策略已阻止从源'http:// localhost:4200'访问'http:// localhost:8081 / demo / customer'处的XMLHttpRequest:没有'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 :(得分:0)

尝试一下:

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