前言
跨域问题在前后端对接十分普遍。之所以立为解决方案,是因为历史原本的解决跨域的问题,没有效果。
实现
import "github.com/gin-contrib/cors"
// r.Use(AllowAll())
func AllowAll() gin.HandlerFunc{
cfg := cors.Config{
AllowMethods: []string{"*"},
AllowHeaders: []string{"*"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}
cfg.AllowAllOrigins = true
return cors.New(cfg)
}
以下是无效方案:
无效1
w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
w.Header().Set("content-type", "application/json") //返回数据格式是json
无效2
import "github.com/rs/cors"
s := &http.Server{
// :8112默认
Addr: httpPort,
Handler: cors.AllowAll().Handler(router),
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 21,
}
fmt.Println("listen on " + httpPort)
if e := s.ListenAndServe(); e != nil {
panic(e)
}
无效3
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
if 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")
}
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}