func Cors() gin.HandlerFunc {
   return func(c *gin.Context) {
      method := c.Request.Method
      origin := c.Request.Header.Get("Origin") //请求头部
      if origin != "" {
         // 当Access-Control-Allow-Credentials为true时
         c.Header("Access-Control-Allow-Origin", "http://【自己的域名/ip,不要加端口号】") 
         c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
         c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-Extra-Header, 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.Header("Access-Control-Max-Age", "86400") // 可选
         c.Set("content-type", "application/json") // 可选
      }

      if method == "OPTIONS" {
         c.AbortWithStatus(http.StatusNoContent)
      }

      c.Next()
   }
}


func main() {
  r := gin.Default()
  r.Use(Cors()) //开启中间件 允许使用跨域请求
  // 其他路由设置
  r.run()
}


来源链接:https://juejin.cn/post/7028523881015017509

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐