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

如何解决Go Gin后端API的CORS跨域访问限制问题?

解决Gin后端CORS跨域错误的方案

问题根源

前端请求被CORS策略拦截,核心原因是后端未返回Access-Control-Allow-Origin等必要跨域响应头,浏览器因此拒绝处理跨域请求。

解决步骤

1. 安装Gin官方CORS中间件

使用Gin社区维护的gin-contrib/cors包处理跨域逻辑,执行以下命令安装:

go get github.com/gin-contrib/cors

2. 在main.go中配置并启用CORS中间件

修改main.go,在路由注册前添加CORS中间件配置(确保所有路由都能继承跨域规则):

package main

import (
	"os"
	"github.com/gin-gonic/gin"
	"github.com/gin-contrib/cors" // 导入CORS包
	"github.com/guilherm5/brapoio/routes"
)

func main() {
	Router := gin.New()

	// 配置CORS规则
	config := cors.DefaultConfig()
	// 允许的前端源:开发环境用localhost,生产环境通过环境变量指定实际域名
	allowedOrigin := os.Getenv("ALLOWED_ORIGIN")
	if allowedOrigin == "" {
		allowedOrigin = "https://localhost:8080"
	}
	config.AllowOrigins = []string{allowedOrigin}
	// 允许的HTTP方法
	config.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}
	// 允许的请求头(包含Authorization适配JWT认证)
	config.AllowHeaders = []string{"Origin", "Content-Type", "Authorization"}
	// 允许携带凭证(如Cookie、JWT)
	config.AllowCredentials = true

	// 启用CORS中间件(必须在路由注册前执行)
	Router.Use(cors.New(config))

	// 原有日志中间件
	Router.Use(gin.LoggerWithWriter(gin.DefaultErrorWriter))

	// 注册所有路由
	routes.ConfiguracaoSistema(Router)
	routes.ConfiguracaoModulo(Router)
	routes.ModuloSistema(Router)
	routes.ArvoreMenu(Router)
	routes.ModuloArvoreMenu(Router)

	routes.Usuario(Router)
	routes.EmpresaUsuario(Router)
	routes.CampoTabelaUsuario(Router)
	routes.ProgramaUsuario(Router)
	routes.FuncionalidadeProgramaUsuario(Router)
	routes.TabelaUsuario(Router)
	routes.ParametroFiltroTabelaUsuario(Router)
	routes.JWTAutentication(Router)

	listenAddr := ":1000"
	if val, ok := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT"); ok {
		listenAddr = ":" + val
	}

	Router.Run(listenAddr)
}

3. 生产环境适配

部署到Azure时,通过环境变量ALLOWED_ORIGIN设置实际前端域名(例如https://your-frontend-domain.com),避免使用*通配符(存在安全风险)。

额外说明

  • 该中间件会自动处理浏览器发送的OPTIONS预检请求,无需手动编写对应路由。
  • 若Azure网关或反向代理有额外CORS配置,需确保后端配置与网关规则一致,避免响应头冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:25:11