'http://localhost:4200'已被 CORS 策略阻止:请求的资源上不存在'Access-Control-Allow-Origin'标头



我正在使用angular for client和Java作为后端服务,以解决以下问题。我浏览了所有可用的在线资源,但运气不好,任何帮助都将不胜感激。";访问位于"的XMLHttpRequesthttp://localhost:8081/demo/customer'来自原点'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);
}
}

试试这个:

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

相关内容

  • 没有找到相关文章

最新更新