gin框架中間件解決跨域問題


http://www.niu12.com/article/45
// 初始化router
router := gin.New()

router.Use(gin.Logger())

router.Use(gin.Recovery())

// 使用跨域中間件
router.Use(cors.Cors())
package cors

import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)

// 處理跨域請求,支持options訪問
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
fmt.Println(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, PUT, PATCH, DELETE")
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()
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM