前后端分离,后端使用Gin,POST的接口老是OPTIONS返回404,用postman测试接口正常,最后发现,跨域中间键一定要在你路由组(group)之前全局使用。
关键代码如下:
- router.go
package Router
import (
"github.com/gin-gonic/gin"
"gin/Controllers"
"gin/Middlewares"
)
func InitRouter() {
router := gin.Default()
// 要在路由组之前全局使用「跨域中间件」, 否则OPTIONS会返回404
router.Use(Middlewares.Cors())
v1 := router.Group("v1")
{
v1.GET("/jsontest", Controllers.JsonTest)
v1.POST("/jsonposttest", Controllers.JsonPostTest)
}
router.Run(":8080")
}
- corsMIddleware.go
package Middlewares
import (
"github.com/gin-gonic/gin"
"net/http"
)
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
if origin != "" {
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
c.Header("Access-Control-Allow-Credentials", "false")
c.Set("content-type", "application/json")
}
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}
有疑问加站长微信联系(非本文作者)