为什么在使用 CORS 时 go 服务器响应 307

Why go server responds with 307 when CORS used

我有一个非常简单的带有 CORS 中间件的应用程序,它似乎可以正常工作并且预检请求按预期工作。但由于某种原因,服务器根据实际请求以 307 响应。在浏览器中重现,邮递员作品正确。

func main() {
    router := gin.Default()
    router.Use(CORSMiddleware())

    accountsGroup := router.Group("/accounts")
    accountsGroup.POST("/", postAccount)
    router.Run("localhost:8080")
}

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()
}


func postAccount(c *gin.Context) {
    response := gin.H{"id": 1}
    c.IndentedJSON(http.StatusCreated, response)
}

预检响应

实际请求

服务器日志

[GIN-debug] Listening and serving HTTP on localhost:8080
[GIN] 2022/04/17 - 16:50:45 | 204 |            0s |       127.0.0.1 | OPTIONS  "/accounts"
[GIN-debug] redirecting request 307: /accounts/ --> /accounts/
[GIN] 2022/04/17 - 16:52:55 | 204 |            0s |       127.0.0.1 | OPTIONS  "/accounts"
[GIN-debug] redirecting request 307: /accounts/ --> /accounts/

您已在 /accounts/ 下注册处理程序,但您正在向 /accounts 发出请求。这与默认设置为 trueRedirectTrailingSlash 设置相结合是导致重定向的原因。

Enables automatic redirection if the current route can't be matched but a handler for the path with (without) the trailing slash exists. For example if /foo/ is requested but a route only exists for /foo, the client is redirected to /foo with http status code 301 for GET requests and 307 for all other request methods.