gpt4 book ai didi

go - Cors 不适用于 gin 和 golang 组路由

转载 作者:IT王子 更新时间:2023-10-29 02:19:46 34 4
gpt4 key购买 nike

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

No 'Access-Control-Allow-Origin'

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

错误是

enter image description here

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

最佳答案

好的,所以我尝试复制这个,发现我的 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)
}

所以你可以在末尾没有正斜杠的情况下发送请求:)

关于go - Cors 不适用于 gin 和 golang 组路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54665442/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com