Golang 框架 Gin 跨域問題 cors
問題
POST的接口老是OPTIONS返回404,用postman測試接口正常,最後發現,跨域中間鍵一定要在你路由組(組)之前使用。
cors中間層
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Add("Access-Control-Allow-Origin", "*")
c.Next()
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
fmt.Println("====> origin", origin)
if origin != "" {
c.Header("Access-Control-Allow-Origin", 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", "false")
c.Set("content-type", "application/json")
}
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}
router
r := gin.Default()
r.Use(corsAuth.Cors())
v1Group := r.Group("/v1/api")
v1Group.POST("/admin/login", admin.Login)