CORS配置指南

CORS响应头参考

响应头示例作用
Access-Control-Allow-Originhttps://app.com or *允许的来源
Access-Control-Allow-MethodsGET, POST, PUT, DELETE允许的HTTP方法
Access-Control-Allow-HeadersContent-Type, Authorization允许的请求头
Access-Control-Allow-Credentialstrue允许Cookie/认证
Access-Control-Max-Age86400预检缓存时间(秒)
Access-Control-Expose-HeadersX-Request-IdJS可访问的响应头

Go/Gin CORS中间件

func CORSMiddleware(allowedOrigins []string) gin.HandlerFunc {
    return func(c *gin.Context) {
        origin := c.Request.Header.Get("Origin")

        // Check if origin is allowed
        for _, allowed := range allowedOrigins {
            if origin == allowed {
                c.Header("Access-Control-Allow-Origin", origin)
                c.Header("Vary", "Origin")
                break
            }
        }

        c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
        c.Header("Access-Control-Allow-Headers", "Content-Type,Authorization,X-Request-ID")
        c.Header("Access-Control-Max-Age", "86400")

        // Handle preflight
        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }
        c.Next()
    }
}

常见CORS错误与解决方案

错误:无Access-Control-Allow-Origin头

解决:服务器添加CORS中间件,确保处理OPTIONS预检请求。

错误:通配符来源与凭证冲突

解决:使用凭证时不能用通配符(*),必须指定具体来源。

错误:请求头不被允许

解决:在预检响应的Access-Control-Allow-Headers中添加该请求头。