最近的项目出现了一个问题,前端发来一个 GET
请求,但是后端只接收到了一个 OPTIONS
请求,并返回 404
,经过简单分析后,发现这是跨域问题,这里我们前端用的框架是Vue3,在修改 header
后,会先发送一个 OPTIONS
请求,再发送 GET
请求,我就是卡在了这里。解决的方法很简单,在路由使用之前添加一个中间件即可
附上当时的Log:
2021-09-17T23:05:20.954+0800 INFO zap@v0.0.1/zap.go:46 /xxx {"status": 404, "method": "OPTIONS", "path": "/xxx", "query": "", "ip": "120.236.177.100", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36", "time": "2021-09-17T23:05:20+08:00", "latency": 0.000011207}
middleware/cros/Cros.go
package cros
import (
"github.com/gin-gonic/gin"
"net/http"
)
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
//放行所有OPTIONS方法
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
// 处理请求
c.Next()
}
}
routers/router.go
package routers
import (
"kakkk-test/common/middleware/cros"
"kakkk-test/controller"
"github.com/gin-gonic/gin"
)
func SetupRouter() *gin.Engine {
r := gin.New()
r.Use(cros.Cors())
r.GET("xxx", controller.XXXHandler)
//一些其他代码
return r
}