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 關注
- 233 瀏覽
添加回答
舉報
