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

GCP Cloud Run中GoLang服务的CORS问题排查求助

GCP Cloud Run部署后CORS失效及302重定向问题

问题描述

  • 本地环境下后端CORS配置正常,通过环境变量指定前端URL,部署到GCP Cloud Run后出现多次302重定向,最终请求失败,即使设置允许所有源(*)也无法解决
  • 请求中未发现Origin和Access-Control-Allow-Origin请求头,怀疑后端代码中if origin != ""的判断因origin为空,导致后续CORS逻辑未执行,但本地环境中请求是带有Origin头的
  • 尝试通过Serverless VPC访问API,问题仍存在;推测需要将VPC的主机名加入API的信任源列表,但仅能获取到VPC的IP段,无法获取对应主机名

相关代码配置

后端Go语言CORS中间件

func (app *MiddleWare) EnableCORS(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        clog := log.GetLoggerFromContext(r.Context())

        w.Header().Add("Vary", "Origin")

        w.Header().Add("Vary", "Access-Control-Request-Method")

        origin := r.Header.Get("Origin")

        if origin != "" {
            clog.InfoCtx("origin", log.Ctx{
                "origin": origin,
            })

            for i := range app.cfg.Cors.TrustedOrigins {
                if origin == app.cfg.Cors.TrustedOrigins[i] {
                    w.Header().Set("Access-Control-Allow-Origin", origin)

                    clog.InfoCtx("Access-Control-Allow-Origin", log.Ctx{
                        "origin": origin,
                    })

                    if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {

                        clog.InfoCtx("Access-Control-Request-Method is not empty", log.Ctx{
                            "value": r.Header.Get("Access-Control-Request-Method"),
                        })

                        w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, PATCH, DELETE")
                        w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
                        w.WriteHeader(http.StatusOK)

                        return
                    }

                    break
                }
            }
        }

        next.ServeHTTP(w, r)
    })
}

前端Nginx配置

location ~ ^/(v1)/ {
     error_log /var/log/nginx/debug.log debug;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header X-Forwarded-Proto $scheme;
     proxy_set_header Host $http_host;
     proxy_set_header X-NginX-Proxy true;

     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection $connection_upgrade;

     proxy_redirect off;
     proxy_pass http://api;

     add_header Cache-Control "no-store, no-cache, must-revalidate";
     add_header Access-Control-Allow-Origin "$http_origin" always;

     expires off;
 }

请求截图

请求重定向失败截图

更新1

尝试通过Serverless VPC访问API,问题依旧;推测需要将VPC的主机名加入API的信任源列表,但仅能获取到VPC的IP段,无法获取对应主机名


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:43:20