go - gin-contrib/cors 返回 404

标签 go cors go-gin

我有一个 golang REST API,它实现了 gin-contrib/cors。但是当我调用 POST 请求时,预检请求 (OPTIONS) 返回 404 结果。

这是一个实现的片段:

engine := gin.New()
group := engine.Group("/api/v1")

// Recovery middleware recovers from any panics and writes a 500 if there was one.
group.Use(gin.Recovery())

// Set cors and db middleware
engine.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"*"},
    AllowMethods:     []string{"*"},
    AllowHeaders:     []string{"*"},
    AllowCredentials: true,     
    MaxAge: 12 * time.Hour,
}))

// Register routes
group.POST("/customers", ctrl.SendRequest)

最佳答案

engine := gin.New()

engine.Use(func(c *gin.Context) {
    c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
    c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
    c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
    c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

    if c.Request.Method == "OPTIONS" {
        c.AbortWithStatus(204)
        return
    }

    c.Next()
})

确保在添加组之前添加 CORS 中间件

关于go - gin-contrib/cors 返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55347167/

相关文章:

go - 在 Golang 中使用 Gin gonic 和一些调度器

go - 如何正确使用 channel 来控制并发?

pointers - 在 Go HTTP 处理程序中,为什么 ResponseWriter 是一个值,而 Request 是一个指针?

go - golang中如何生成多个uuid和md5文件

ajax - Cloudfront 拒绝来自一个域的 CORS,但不拒绝来自另一个域的 CORS

Golang gin gonic web 框架代理路由到另一个后端

go - 无法将 int 分配给 Go 中的变量

javascript - xmlHttpRequest 出现 Phonegap 错误

javascript - S3 : No Access-Control-Allow-Origin header is present on the requested resource

go - 来自 xx.xx.xx.xx :14333: EOF 的 TLS 握手错误