【发布时间】:2023-05-08 19:14:01
【问题描述】:
我试图在我的 Angular 前端和 Java / Spring 中的 REST 端点之间建立连接(我没有开发,也不太了解)。通过 GET,一切正常。通过 POST,我在终端收到消息
已被 CORS 政策阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
并且,在开发工具的“网络”选项卡中,OPTIONS 方法出现错误 403
Request Method: OPTIONS
Status Code: 403
Remote Address: xx.xx.xx.xx:xxxx
Referrer Policy: strict-origin-when-cross-origin
所以,我在互联网上多次搜索后发现了这种情况,原因是 CORS 设置:通常,在这种情况下,OPTIONS 调用在 POST 之前发送;但是,由于 CORS,不允许调用 OPTIONS。所以,我试图在我的控制器上设置这一行
@CrossOrigin(origins = "*", methods = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
这次错误发生了变化
Multiple CORS header 'Access-Control-Allow-Origin' not allowed
But the code I added is the only similar to @CrossOrigin, I dind't found others similar.
所以,根据CORS issue - No 'Access-Control-Allow-Origin' header is present on the requested resource的帖子,我尝试了以下解决方案:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}
和
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable();
http.cors();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of("*"));
configuration.setAllowedMethods(ImmutableList.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(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
但是这次我在控制台看到的错误变成了
已被 CORS 策略阻止:“Access-Control-Allow-Origin”标头包含多个值“*、*”,但只允许一个。
所以,这是我到达的最后一点。如何解决关于多个值的最后一个错误?每次我处理这个问题时,我都会提前一步,错误会发生变化,但它仍然存在。
【问题讨论】:
-
您能否将带有标题的请求添加到您的问题中。
origin标头的值是多少?还添加带有标题的响应?回复中有多少Access-Control-Allow-Origin? -
您可以尝试删除
@CrossOrigin(origins = "*", methods = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})。 -
看起来你有两个不同的过滤器,添加
Access-Control-Allow-Origin标题。
标签: java spring spring-security cors