cors icon indicating copy to clipboard operation
cors copied to clipboard

[handlePreflight] AbortWithStatus should be come after setting preflightHeaders

Open peanutzhen opened this issue 2 years ago • 1 comments

func handlePreflight(c *gin.Context, s *settings) bool {
	c.AbortWithStatus(200)
	if !s.validateMethod(c.Request.Header.Get("Access-Control-Request-Method")) {
		return false
	}
	if !s.validateHeader(c.Request.Header.Get("Access-Control-Request-Header")) {
		return false
	}
	for key, value := range s.preflightHeaders {
		c.Writer.Header()[key] = value
	}
	return true
}

When the Options method requested, the browser returns: image

But I Allow this method and headers:

CorsMws = cors.New(cors.Config{
		AllowedOrigins: []string{conf.WebAddress},
		AllowedMethods: []string{"GET", "POST", "OPTIONS", "PUT", "DELETE", "UPDATE"},
		AllowedHeaders: []string{"Authorization", "Content-Type", "Upgrade", "Origin",
			"Connection", "Accept-Encoding", "Accept-Language", "Host", "Access-Control-Request-Method", "Access-Control-Request-Headers"},
		ExposedHeaders: []string{"Content-Length"},
		MaxAge:         12 * time.Hour,
})

peanutzhen avatar Feb 14 '22 08:02 peanutzhen

// CORS middleware
	CorsMws = func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", conf.WebAddress)
		c.Writer.Header().Set("Access-Control-Max-Age", "86400")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, Authorization")
		c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(200)
		} else {
			c.Next()
		}
	}

But it works for me.

peanutzhen avatar Feb 14 '22 16:02 peanutzhen