您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“Golang gin跨域問題怎么解決”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Golang gin跨域問題怎么解決”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。
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) //主要設(shè)置Access-Control-Allow-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() } }
func Cors() gin.HandlerFunc { return cors.New(cors.Config{ AllowAllOrigins: false, AllowOrigins: nil, AllowOriginFunc: func(origin string) bool { return true }, AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"}, AllowHeaders: []string{"Authorization", "ts", "Accept", "Origin", "DNT", "X-CustomHeader", "Keep-Alive", "User-Agent", "X-Requested-With", "If-Modified-Since", "Cache-Control", "Content-Type", "Content-Range", "Range"}, AllowCredentials: true, MaxAge: 10 * time.Minute, }) }
package router import ( "github.com/gin-gonic/gin" "goproejct/controllers" "goproejct/middlewares"//引入中間件goproject是項目名 根據(jù)自己情況 ) func InitRouter() { router := gin.Default() router.Use(Cors())//使用中間件 v1 := router.Group("v1") { v1.POST("/login", controllers.Login) v1.POST("/regist", controllers.Regist) } router.Run(":8000") }
讀到這里,這篇“Golang gin跨域問題怎么解決”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。