【发布时间】:2021-09-03 14:44:56
【问题描述】:
我构建了一个简单的 Spring Boot rest api,并有一个 Angular 应用程序从另一个本地端口(全部在本地运行)发出 http 请求。我的@SpringBootApplicationclass 中有以下 CORS 过滤器,以允许来自我的 Angular 应用程序的请求,并且一切正常。
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control-Allow-Origin", "Content-Type",
"Accept", "Authorization", "Origin, Accept", "X-Requested-With",
"Access-Control-Request-Method", "Access-Control-Request-Headers"));
corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization",
"Access-Control-Allow-Origin", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials"));
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
然后我添加了 Spring Security,因为我想保护我的 api。现在我不断收到Access to XMLHttpRequest has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我花了几乎一整天的时间试图在 Spring 文档中解决这个问题,但我显然做错了什么。
根据这篇文章,我用@Bean 替换了我的 CORS 过滤器,但无济于事,我仍然遇到相同的 CORS 错误。
Spring security CORS Filter
例如在我的 @SpringBootApplication 带注释的类中,我删除了旧的 cors 过滤器并添加了:
@Bean
public WebMvcConfigurer configure() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:4200"); //Angular app port
}
};
}
我可以通过浏览器从后端服务的端口 (8080) 向我的 api 发出请求,问题是我在端口 4200 上运行的 Angular 应用程序正在向后端发出请求,但由于 CORs 过滤器而被阻止。我还有什么需要配置的吗?
【问题讨论】:
标签: angular spring-boot cors