Cors 不适用于 gin 和 golang 组路由

我尝试了这个特定的代码,但它一直给我错误


没有“访问控制允许来源”


package main


import (

    "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)

    }

}

错误是

http://img.mukewang.com/647db9ef00018d1914730070.jpg

我的前端是用 Vue.js 编写的,运行在localhost:8000本地主机上,服务器运行在localhost:9000



千万里不及你
浏览 176回答 3
3回答

慕标5832272

好吧,所以我尝试复制这个,发现我做的 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)}所以你可以在末尾发送没有正斜杠的请求:)

皈依舞

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

慕神8447489

I&nbsp;tried&nbsp;so&nbsp;many&nbsp;things&nbsp;and&nbsp;finally&nbsp;this&nbsp;worked&nbsp;for&nbsp;me:func&nbsp;CORSConfig()&nbsp;cors.Config&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;corsConfig&nbsp;:=&nbsp;cors.DefaultConfig() &nbsp;&nbsp;&nbsp;&nbsp;corsConfig.AllowOrigins&nbsp;=&nbsp;[]string{"http://localhost:3000"} &nbsp;&nbsp;&nbsp;&nbsp;corsConfig.AllowCredentials&nbsp;=&nbsp;true &nbsp;&nbsp;&nbsp;&nbsp;corsConfig.AddAllowHeaders("Access-Control-Allow-Headers",&nbsp;"access-control-allow-origin,&nbsp;access-control-allow-headers",&nbsp;"Content-Type",&nbsp;"X-XSRF-TOKEN",&nbsp;"Accept",&nbsp;"Origin",&nbsp;"X-Requested-With",&nbsp;"Authorization") &nbsp;&nbsp;&nbsp;&nbsp;corsConfig.AddAllowMethods("GET",&nbsp;"POST",&nbsp;"PUT",&nbsp;"DELETE") &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;corsConfig }在 func main 中添加:r = 杜松子酒。默认()r.Use(cors.New(CORSConfig()))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go