CORS反应和杜松子酒杜松子酒

发布于 2025-01-27 12:22:01 字数 2933 浏览 4 评论 0原文

我已经遇到了一个问题,该问题在开发环境中,反应前端和go-lang gin-gin-gon-gonic框架之间实现了越野资源共享,下面是浏览器的控制台日志

”这是从GO框架中收到的请求,可以看出,未经验证的前飞行请求“未经验证”

邮政请求

console log from react react应用程序发送 可以看出,从GO框架收到的请求未验证

我尝试了两个黑客,一个正在验证前飞行请求,并通过React选项获得200,如下所示,

func preflight(c *gin.Context) {
    c.Header("Access-Control-Allow-Origin", "*")
    c.Header("Access-Control-Allow-Headers", "access-control-allow-origin, access-control-allow-headers")
    c.JSON(http.StatusOK, struct{}{})
}

此hack没有帮助,此外,我在访问控件中包括一个带有通配符域的中间件允许来源,以及http:// localhost:3000:如下所示,

func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {

        c.Header("Access-Control-Allow-Origin", "*")
        c.Header("Access-Control-Allow-Credentials", "true")
        c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT")

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

        c.Next()
    }
}

我还尝试了GIN CORS软件包,如下所示,如下所示该请求仍被阻止

“服务器中的ajax响应”

These are part of my routes 

    r := gin.Default()
    //r := gin.New()

    config := cors.DefaultConfig()
    config.AllowOrigins = []string{"*"}
    // config.AllowOrigins = []string{"http://google.com", "http://facebook.com"}
    // config.AllowAllOrigins = true
    r.Use(cors.New(config))

    //system routes
    router.NotFound(r)
    router.NoMethods(r)

    //static routes
    router.ServeStatic(r)
Methods 

func NotFound(route *gin.Engine) {
    route.NoRoute(func(c *gin.Context) {
        c.JSON(404, gin.H{"msg": "Not Found"})
    })
}

func NoMethods(route *gin.Engine) {
    route.NoMethod(func(c *gin.Context) {
        c.JSON(405, gin.H{"msg": "Not allowed"})
    })
}

//Serve frontend static files

func ServeStatic(route *gin.Engine) {
    route.Use(static.Serve("/", static.LocalFile("./views/public", true)))
    route.Use(auth.CORSMiddleware())
    api := route.Group("/api")

    {
        api.GET("/", func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{
                "message": "pong",
            })
        })
    }

GO版本是GO版本GO1.18.1 Linux/AMD64

"axios": "^0.24.0",
"react": "^18.1.0",

I have run into a problem implementing cross origin resource sharing in the development environment, between a react front end and Go-lang Gin-Gonic framework, below is the console log from the browser
Console log for react application sending a post request

This is the received request from the Go framework, as can be seen, the preflight request is not validated

Console log from the react application sending a post request

This is the received request from the Go framework, as can be seen, the preflight request is not validated

I have attempted two hacks, one is validating the preflight request and passing a 200 on the react OPTIONS as seen below

func preflight(c *gin.Context) {
    c.Header("Access-Control-Allow-Origin", "*")
    c.Header("Access-Control-Allow-Headers", "access-control-allow-origin, access-control-allow-headers")
    c.JSON(http.StatusOK, struct{}{})
}

This hack was not of help, additionally ,i included a middleware with a wildcard domain in the access control allow origin, as well as with http://localhost:3000 as shown below

func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {

        c.Header("Access-Control-Allow-Origin", "*")
        c.Header("Access-Control-Allow-Credentials", "true")
        c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT")

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

        c.Next()
    }
}

I also tried the gin cors package as shown here github.com/gin-contrib/cors but the request is still being blocked

ajax response from the server

These are part of my routes 

    r := gin.Default()
    //r := gin.New()

    config := cors.DefaultConfig()
    config.AllowOrigins = []string{"*"}
    // config.AllowOrigins = []string{"http://google.com", "http://facebook.com"}
    // config.AllowAllOrigins = true
    r.Use(cors.New(config))

    //system routes
    router.NotFound(r)
    router.NoMethods(r)

    //static routes
    router.ServeStatic(r)
Methods 

func NotFound(route *gin.Engine) {
    route.NoRoute(func(c *gin.Context) {
        c.JSON(404, gin.H{"msg": "Not Found"})
    })
}

func NoMethods(route *gin.Engine) {
    route.NoMethod(func(c *gin.Context) {
        c.JSON(405, gin.H{"msg": "Not allowed"})
    })
}

//Serve frontend static files

func ServeStatic(route *gin.Engine) {
    route.Use(static.Serve("/", static.LocalFile("./views/public", true)))
    route.Use(auth.CORSMiddleware())
    api := route.Group("/api")

    {
        api.GET("/", func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{
                "message": "pong",
            })
        })
    }

The go version is go version go1.18.1 linux/amd64

"axios": "^0.24.0",
"react": "^18.1.0",

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

话少心凉 2025-02-03 12:22:01

尝试在句柄示例之前移动CORS中间件

func (h *Handler) InitRoutes() *gin.Engine {
    router := gin.New()

    router.Use(h.setHeaders)

    router.GET("/", h.getRecordsByFilter)
    router.GET("/:uuid", h.getRecordByUuid)
    router.POST("/", h.createRecord)
    router.PUT("/:uuid", h.updateRecord)
    router.DELETE("/:uuid", h.deleteRecord)

    return router
}

Try to move CORS middleware before your handleFunc

Example:

func (h *Handler) InitRoutes() *gin.Engine {
    router := gin.New()

    router.Use(h.setHeaders)

    router.GET("/", h.getRecordsByFilter)
    router.GET("/:uuid", h.getRecordByUuid)
    router.POST("/", h.createRecord)
    router.PUT("/:uuid", h.updateRecord)
    router.DELETE("/:uuid", h.deleteRecord)

    return router
}
陌路黄昏 2025-02-03 12:22:01

问题在于,凭据是前端的真实条件

handleSubmit(event) {
    const {email,password} = this.state;
    axios.post("http://localhost:3000/auth/register",
    {email: email, password: password},{
        withCredentials: true}).then(response => {
            console.log("registration res", response);
            console.log("response data",response.data);
        }).catch(error => {
            console.log("registratino error", error);
        });


    event.preventDefault();
}

The problem was with credentials true from the react front-end

handleSubmit(event) {
    const {email,password} = this.state;
    axios.post("http://localhost:3000/auth/register",
    {email: email, password: password},{
        withCredentials: true}).then(response => {
            console.log("registration res", response);
            console.log("response data",response.data);
        }).catch(error => {
            console.log("registratino error", error);
        });


    event.preventDefault();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文