亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Cors 不適用于 gin 和 golang 組路由

Cors 不適用于 gin 和 golang 組路由

Go
千萬里不及你 2023-06-05 18:32:56
我嘗試了這個特定的代碼,但它一直給我錯誤沒有“訪問控制允許來源”package mainimport (    "github.com/gin-contrib/cors"    "github.com/gin-gonic/gin")func main() {    router := gin.Default()    router.Use(cors.Default())    v1 := router.Group("/api/products")    {        v1.GET("/", ListOfProducts)        v1.POST("/post",AddProduct)    }}錯誤是我的前端是用 Vue.js 編寫的,運行在localhost:8000本地主機上,服務器運行在localhost:9000
查看完整描述

3 回答

?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

好吧,所以我嘗試復制這個,發現我做的 AJAX 請求是錯誤的,可能你犯了和我一樣的錯誤:


使用類似的配置:


func main() {

    router := gin.Default()

    router.Use(cors.Default())


    v1 := router.Group("/api")

    {

        v1.GET("/", func(c *gin.Context) {

            c.String(http.StatusOK, "Hello world")

        })

    }


    router.Run()

}

此 AJAX 請求將拋出您收到的 CORS 錯誤:


$.get('http://localhost:8080/api').then(resp => {

  console.log(resp);

});

但是在末尾添加一個“/”就可以了:


$.get('http://localhost:8080/api/').then(resp => {

  console.log(resp);

});

因此,在您的情況下,請嘗試請求 URL:(http://localhost:9000/api/products/末尾帶有正斜杠)


此外,您還可以將路線修改為如下所示:


v1 := router.Group("/api")

{

    v1.GET("/products", ListOfProducts)

    v1.POST("/products/post",AddProduct)

}

所以你可以在末尾發送沒有正斜杠的請求:)


查看完整回答
反對 回復 2023-06-05
?
皈依舞

TA貢獻1851條經驗 獲得超3個贊

r.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"http://localhost:<your_port>"},
    AllowMethods:     []string{http.MethodGet, http.MethodPatch, http.MethodPost, http.MethodHead, http.MethodDelete, http.MethodOptions},
    AllowHeaders:     []string{"Content-Type", "X-XSRF-TOKEN", "Accept", "Origin", "X-Requested-With", "Authorization"},
    ExposeHeaders:    []string{"Content-Length"},
    AllowCredentials: true,
}))

嘗試這個


查看完整回答
反對 回復 2023-06-05
?
慕神8447489

TA貢獻1780條經驗 獲得超1個贊

I tried so many things and finally this worked for me:func CORSConfig() cors.Config {
    corsConfig := cors.DefaultConfig()
    corsConfig.AllowOrigins = []string{"http://localhost:3000"}
    corsConfig.AllowCredentials = true
    corsConfig.AddAllowHeaders("Access-Control-Allow-Headers", "access-control-allow-origin, access-control-allow-headers", "Content-Type", "X-XSRF-TOKEN", "Accept", "Origin", "X-Requested-With", "Authorization")
    corsConfig.AddAllowMethods("GET", "POST", "PUT", "DELETE")
        return corsConfig
}

在 func main 中添加:

r = 杜松子酒。默認()

r.Use(cors.New(CORSConfig()))


查看完整回答
反對 回復 2023-06-05
  • 3 回答
  • 0 關注
  • 219 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號