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")
|
2024-04-09 10:17:08 +00:00
|
|
|
c.Header("Access-Control-Allow-Headers", "*")
|
2024-04-09 05:38:29 +00:00
|
|
|
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")
|
2024-04-09 10:17:08 +00:00
|
|
|
c.Header("Access-Control-Allow-Headers", "*")
|
2024-04-09 05:38:29 +00:00
|
|
|
c.Header("Access-Control-Allow-Credentials", "true")
|
|
|
|
c.Next()
|
|
|
|
})
|
|
|
|
}
|