cors
cors copied to clipboard
[handlePreflight] AbortWithStatus should be come after setting preflightHeaders
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:
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,
})
// 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.