求解:go-gin 跨域问题 OPTIONS 通过 POST 未通过

go-gin 跨域 OPTIONS 通过 POST 未通过

// 跨域中间件
func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        //请求方法
        method := c.Request.Method
        //请求头部
        origin := c.Request.Header.Get("Origin")

        if origin != "" {
            fmt.Println("origin=>",origin)
            fmt.Println()
            // gin设置响应头,设置跨域
            c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
            c.Header("Access-Control-Allow-Origin", origin)
            c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
            c.Header("Access-Control-Allow-Headers", "token,source,Origin, X-Requested-With, 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,Expires,Last-Modified,Pragma,FooBar")
        }

        //放行所有OPTIONS方法
        if method == "OPTIONS" {
            c.JSON(http.StatusOK, "Options Request!")
            //return
        }
        status := c.Writer.Status()
        log.Println("==", status)
        // c.Next()后就执行真实的路由函数
        c.Next()
    }
}
//路由
func Router() *gin.Engine {
    router := gin.Default()
    store := router.Group("/store")
    {
        store.POST("/login", controllers.StoreLogin)
    }

    // 跨域中间件
    router.Use(middleware.Cors())
    return router
}
已邀请:

larrydev - 小白

赞同来自: jss

试一下把中间件放到上面注册。然后再注册路由

Swper - It男

赞同来自:

router := gin.Default() router.Use(middleware.Cors())

这样先把中间件放在路由前。

要回复问题请先登录注册