gpt4 book ai didi

go - gin-contrib/cors 返回 404

转载 作者:数据小太阳 更新时间:2023-10-29 03:09:06 31 4
gpt4 key购买 nike

我有一个 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com