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

如何解决Go Gin框架API中缺少Access-Control-Allow-Origin头的跨域问题?

解决Next.js调用Gin API时的CORS跨域问题

问题重现

调用Gin框架开发的API接口 http://localhost:8080/orders?page=10&pageSize=10 时,出现CORS错误:

origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

已尝试gin-contrib/cors、rs/cors及手动设置请求头,均未解决。当前代码使用cors.Default()配置跨域。

解决方案

问题出在cors.Default()的默认配置无法完全匹配你的请求场景(比如带凭证的请求、特定请求头),需要自定义CORS规则,且确保跨域中间件最先注册。

修改后的代码

import (
    "time"
    "github.com/gin-contrib/cors"
    "github.com/gin-gonic/gin"
)

func Init(init *configs.Initialization) *gin.Engine {
    router := gin.New()

    // 自定义CORS配置,精准匹配前端地址
    corsConfig := cors.Config{
        AllowOrigins:     []string{"http://localhost:3000"}, // 明确指定前端域名
        AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, // 允许所有常用HTTP方法
        AllowHeaders:     []string{"Origin", "Content-Type", "Accept", "Authorization"}, // 允许的请求头
        ExposeHeaders:    []string{"Content-Length"},
        AllowCredentials: true, // 如果前端请求带Cookie/凭证,必须开启此项
        MaxAge:           12 * time.Hour, // 预检请求缓存时长
    }
    // 跨域中间件必须第一个注册,确保所有请求先经过CORS处理
    router.Use(cors.New(corsConfig))

    router.Use(gin.Logger())
    router.Use(gin.Recovery())

    orders := router.Group("/orders")
    {
        orders.GET("/", init.OrderController.GetOrders)
        orders.GET("/:orderID", init.OrderController.GetOrder)
    }

    return router
}

关键注意事项

  1. 中间件顺序:CORS中间件必须放在Logger、Recovery等其他中间件之前,否则请求可能先被其他逻辑拦截,无法生成CORS响应头。
  2. 精准指定Origin:如果前端请求带凭证(如Cookie),AllowOrigins不能使用*,必须明确写http://localhost:3000。
  3. 预检请求处理:OPTIONS方法必须被允许,浏览器会先发送预检请求验证跨域权限,AllowMethods中必须包含OPTIONS。
  4. 验证响应头:重启API服务后,用浏览器开发者工具查看响应头,确认存在Access-Control-Allow-Origin: http://localhost:3000。

内容的提问来源于stack exchange,提问作者NICOLAS FRANCO RAMPOLDI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:52:15