You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GCS托管Angular向GCF Spring Boot API发POST请求遇CORS问题

问题:GCP存储桶静态页面调用Cloud Function(Spring Boot)时的CORS错误

场景描述

最终目标是让GCP存储桶中的Angular静态页面向API网关端点发送POST请求,由网关路由至部署为Cloud Function的Spring Boot REST API。当前为简化测试,直接绕过API网关调用Cloud Function,但点击页面发送按钮时触发CORS错误。

错误信息

Access to XMLHttpRequest at 'https://my-gcf-endpoint/post' from origin
'https://storage.googleapis.com' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: It does not have HTTP ok status.

已尝试的配置

1. GCP存储桶CORS配置

创建cors.json配置文件:

[
    {
      "origin": ["*"],
      "method": ["GET", "POST"],
      "responseHeader": ["*"],
      "maxAgeSeconds": 3600
    }
]

通过命令 gsutil cors set cors-json-file gs://<bucket_name> 分别为前端、后端存储桶配置CORS(已确认在配置文件本地目录通过Cloud SDK执行命令)。

2. Spring Boot应用CORS配置

全局配置(主类)

@SpringBootApplication
public class DivrFunctionApplication {

    public static void main(String[] args) {
        SpringApplication.run(DivrFunctionApplication.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedHeaders("*")
                        .allowedMethods("*");
            }
        };
    }
}

控制器配置

@Component
@RestController
@CrossOrigin
public class MainController {

  @PostMapping("/postData")
  public ResponseEntity<String> postText(@RequestBody String message) {
    // 手动添加响应头后仍无效
    HttpHeaders headers = new HttpHeaders();
    headers.set("ACCESS_CONTROL_ALLOW_ORIGIN","*");
    return new ResponseEntity<>(message, headers, HttpStatus.OK);
  }

  @GetMapping("/")
  public String hello() {
    return "hello world!";
  }
}

补充配置

已在application.properties中添加:

spring.mvc.dispatch-options-request=true

环境补充说明

  • 应用为极简配置,无Spring Security及任何认证机制
  • 存储桶均设置为公开,赋予AllUser管理员权限
  • Cloud Function允许未认证访问

提问

请问接下来可以尝试哪些解决方法?

内容的提问来源于stack exchange,提问作者AylaWinters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:25:18