我有一个 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)
Run Code Online (Sandbox Code Playgroud)
小智 6
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()
})
Run Code Online (Sandbox Code Playgroud)
确保在添加组之前添加 CORS 中间件
小智 5
我遇到了完全相同的问题,但定位“组”不是问题。
这是我的代码,其中问题代码被注释掉并替换为手动cors....
// router.Use(cors.New(cors.Config{
// // AllowAllOrigins: true,
// AllowOrigins: []string{"*"},
// AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
// AllowHeaders: []string{"Origin", "Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "ResponseType"},
// ExposeHeaders: []string{"Content-Length"},
// AllowCredentials: true,
// MaxAge: 12 * time.Hour,
// }))
router.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, ResponseType, 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()
})
Run Code Online (Sandbox Code Playgroud)