Vestmore_GO/utils/cors/cors.go

28 lines
976 B
Go
Raw Normal View History

2024-04-09 05:38:29 +00:00
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", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
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", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
c.Header("Access-Control-Allow-Credentials", "true")
c.Next()
})
}