【问题标题】:Access-control-allow-origin not allowed when calling Spring Boot from Angular App [duplicate]从Angular App调用Spring Boot时不允许访问控制允许来源[重复]
【发布时间】:2020-08-15 23:49:36
【问题描述】:

我有一个 Angular 8 应用程序调用 Spring boot REST API,我遇到了 CORS 问题,即使在谷歌搜索后我也无法真正解决。

http://localhost:4200 ---------------> http://localhost:8080

错误说: Access to XMLHttpRequest at 'http://localhost:8080/api/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

我知道在发送实际请求之前会先发送飞行前请求。

我的 Spring Boot 服务器端已经启用了 CORS:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().cors().and().authorizeRequests()
                   ... other configurations
}

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(Collections.singletonList("*")); // Provide list of origins if you want multiple origins
    config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Access-Control-Allow-Headers", "X-Requested-With", "Authorization"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
    config.setAllowCredentials(true);
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

我的 Angular 方面:

login(username, password) {
        const httpOptions = {
            headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Access-Control-Allow-Origin, Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization',
            'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE.OPTIONS'

            })}
        return this.http.post<any>(`http://localhost:8080/api/login`, { username, password }, httpOptions)
            .pipe(map(user => {
                return user;
            }));
    }

【问题讨论】:

  • 在您的前端 JavaScript 代码中,从 headers 块中删除所有 Access-Control-Allow-\* 标头。这些都是响应标头。尝试将它们设置为请求标头是行不通的。
  • 错误说明了问题所在; Access-Control-Allow-Origin 不是允许的标头,并且不在传递给 setAllowedHeaders 的列表中。

标签: angular spring-boot cors


【解决方案1】:

从角度请求中删除您的 Access-Control-Allow -*** 标头。

首先,这些是服务器端标头。但是将它们添加到您的客户请求中也有不利之处。

根据 CORS,如果您想将自定义标头添加到您的请求(即安全列表之外的标头 headersAcceptAccept-LanguageContent-TypeContent-Language),您的服务器应该响应带有Access-Control-Allow-Headersheader 的 OPTIONS 请求,指定接受的自定义标头列表。

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2017-01-10
    • 2020-01-21
    相关资源
    最近更新 更多