Gin框架CORS配置

我在使用Gin框架配置CORS时遇到了问题。按照官方文档设置了以下中间件:

r.Use(cors.Default())

但前端仍然报跨域错误,提示"No ‘Access-Control-Allow-Origin’ header is present"。我尝试了自定义配置:

r.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"*"},
    AllowMethods:     []string{"GET", "POST"},
    AllowHeaders:     []string{"Origin"},
    ExposeHeaders:    []string{"Content-Length"},
    AllowCredentials: true,
}))

还是无法解决问题。请问:

  1. 为什么Default配置不起作用?
  2. 自定义配置还需要设置哪些必要参数?
  3. 如果前端用axios发送请求,需要特别处理吗?
  4. 在生产环境用"*"作为AllowOrigins是否安全?

我的Gin版本是v1.9.1,前端是Vue3项目。


3 回复

在Gin框架中配置CORS(跨域资源共享),你可以使用gin-contrib/cors中间件。首先需要安装该模块:

go get github.com/gin-contrib/cors

然后在你的Gin应用中进行如下配置:

package main

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

func main() {
	r := gin.Default()

	// 配置 CORS
	config := cors.DefaultConfig()
	config.AllowOrigins = []string{"http://example.com"} // 允许的源
	config.AllowMethods = []string{"GET", "POST", "PUT", "DELETE"} // 允许的方法
	config.AllowHeaders = []string{"Authorization", "Content-Type"} // 允许的头部
	config.AllowCredentials = true // 是否允许发送凭据

	r.Use(cors.New(config))

	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})

	r.Run(":8080")
}

这段代码设置了允许http://example.com访问,并支持常见的HTTP方法和头部信息。如果你需要开放所有来源,可以将AllowOrigins设置为[]string{"*"},但这样可能会带来安全风险。


在Gin框架中配置跨域资源共享(CORS)可以通过gin-cors中间件实现。首先,你需要安装gin-cors库:

go get github.com/gin-contrib/cors

然后在初始化路由时进行配置:

package main

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

func main() {
    r := gin.Default()

    // 配置cors
    config := cors.DefaultConfig()
    config.AllowOrigins = []string{"http://example.com"} // 允许的域名
    config.AllowMethods = []string{"GET", "POST", "PUT", "DELETE"} // 允许的方法
    config.AllowHeaders = []string{"Content-Type", "Authorization"} // 允许的header
    config.AllowCredentials = true // 是否允许携带cookie

    r.Use(cors.New(config))

    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })

    r.Run(":8080")
}

这段代码设置了允许example.com域名访问,并允许常见的HTTP方法和头部信息。如果你需要更复杂的规则,可以调整config中的选项。

在Gin框架中配置CORS(跨域资源共享)可以使用官方推荐的cors中间件。以下是完整配置示例:

package main

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

func main() {
	r := gin.Default()

	// 配置CORS中间件
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"https://example.com", "http://localhost:3000"},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},
		AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))

	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})

	r.Run(":8080")
}

关键配置项说明:

  • AllowOrigins: 允许的域名列表
  • AllowMethods: 允许的HTTP方法
  • AllowHeaders: 允许的请求头
  • ExposeHeaders: 暴露给客户端的响应头
  • AllowCredentials: 是否允许发送cookie
  • MaxAge: 预检请求缓存时间

简单配置方式(允许所有跨域请求,适合开发环境):

r.Use(cors.Default())

建议在生产环境中严格限制AllowOrigins,只开放必要的域名。

回到顶部