我有一个非常简单的应用程序,带有 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)
}
Run Code Online (Sandbox Code Playgroud)
飞行前响应
实际要求
服务器日志
[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/
Run Code Online (Sandbox Code Playgroud)
您已在下注册了处理程序,/accounts/但您正在向 发出请求/accounts。RedirectTrailingSlash与默认设置相结合的设置true是导致重定向的原因。
如果当前路由无法匹配,但存在带(不带)尾部斜杠的路径处理程序,则启用自动重定向。例如,如果
/foo/被请求,但仅存在 的路由/foo,则客户端将被重定向到/foo带有 http 状态代码301的GET请求和307所有其他请求方法。
| 归档时间: |
|
| 查看次数: |
2424 次 |
| 最近记录: |