登录
首页 >  Golang >  Go问答

gin-contrib/cors 导致 404 错误

来源:stackoverflow

时间:2024-03-14 14:42:17 376浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《gin-contrib/cors 导致 404 错误》,聊聊,我们一起来看看吧!

问题内容

我有一个 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 中间件

以上就是《gin-contrib/cors 导致 404 错误》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>