Vestmore_GO/utils/cors/cors.go
2024-04-09 18:17:08 +08:00

28 lines
874 B
Go

package cors
import (
"net/http"
"github.com/gin-gonic/gin"
)
func SetCors(router *gin.Engine) {
// 处理前端发送的options请求
router.OPTIONS("/*path", func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*") // 可以根据实际情况改为特定域名
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Header("Access-Control-Allow-Headers", "*")
c.Header("Access-Control-Allow-Credentials", "true")
c.Status(http.StatusOK)
})
// 处理所有的路由请求
router.Use(func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*") // 允许所有域名跨域访问,也可以指定特定的域名
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Header("Access-Control-Allow-Headers", "*")
c.Header("Access-Control-Allow-Credentials", "true")
c.Next()
})
}