go项目添加跨域处理

1.在项目根目录下载依赖

go get github.com/gin-contrib/cors

 

2.在main.go合适位置添加

// 配置 CORS
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"}, // 允许所有来源(生产环境建议改成前端域名如http://localhost:8080)
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))

 

posted @ 2025-06-05 15:56  幽暗天琴  阅读(21)  评论(0)    收藏  举报