package middleware import ( "bytes" "github.com/gin-gonic/gin" "io/ioutil" "log" "net/http" ) func CrossSite(c *gin.Context) { c.Writer.Header().Set("Access-Control-Allow-Origin", "*") //服务器支持的所有跨域请求的方法 c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //允许跨域设置可以返回其他子段,可以自定义字段 c.Header("Access-Control-Allow-Headers", "x-requested-with,Content-Type,Authorization,Content-Length,X-CSRF-Token,Token,session") // 允许浏览器(客户端)可以解析的头部 (重要) c.Header("Access-Control-Expose-Headers", "Content-Length,Access-Control-Allow-Origin,Access-Control-Allow-Headers") c.Header("X-Content-Type-Options", "nosniff") //允许客户端传递校验信息比如 cookie (重要) c.Header("Access-Control-Allow-Credentials", "true") if c.Request.Method == "OPTIONS" { c.JSON(http.StatusOK, "Options Request!") c.Abort() } data, err := c.GetRawData() if err != nil { log.Println(err.Error()) } c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data)) // 关键点 c.Next() }