关于如何处理gin框架前端请求跨域

2022-08-18 17:28:45 浏览数 (2)

关于如何处理gin框架前端请求跨域?

代码语言:javascript复制
// Cors 跨域
func Cors() gin.HandlerFunc {
   return func(c *gin.Context) {
      if c.Request.Header.Get("Origin") != "" {
         c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
         c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
         c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
         c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
         c.Header("Access-Control-Allow-Credentials", "true")
         c.Set("content-type", "application/json")
      }

      if c.Request.Method == http.MethodOptions {
         c.AbortWithStatus(http.StatusNoContent)
      }
      c.Next()
   }

}
代码语言:javascript复制
func main() {
   r := gin.Default()
   // 中间件 处理跨域 
   r.Use(middlewares.Cors())
   port := config.Config.Server.Port
   if port != "" {
      panic(r.Run(":"   port))
   }
   r.Run(config.Config.Server.Port) // listen and serve on 0.0.0.0:8080
}

注意:需要将 r.Use(middlewares.Cors()) 在使用路由前进行设置,否则会导致不生效

0 人点赞