3 回答
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)
}
所以你可以在末尾发送没有正斜杠的请求:)
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, }))
尝试这个
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()))
- 3 回答
- 0 关注
- 175 浏览
添加回答
举报