我尝试这个特定的代码,但它继续给我错误
没有“访问控制允许来源”
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)
}
}
Run Code Online (Sandbox Code Playgroud)
错误是
我的前端是用 Vue.js 编写的并在localhost:8000本地主机上运行,服务器运行在localhost:9000
Car*_*nez 12
好吧,所以我尝试复制这个,发现我的 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()
}
Run Code Online (Sandbox Code Playgroud)
此 AJAX 请求将引发您收到的 CORS 错误:
$.get('http://localhost:8080/api').then(resp => {
console.log(resp);
});
Run Code Online (Sandbox Code Playgroud)
但在最后添加一个“/”就可以了:
$.get('http://localhost:8080/api/').then(resp => {
console.log(resp);
});
Run Code Online (Sandbox Code Playgroud)
因此,在您的情况下,请尝试请求 URL:(http://localhost:9000/api/products/末尾带有正斜杠)
此外,您还可以将路线修改为如下所示:
v1 := router.Group("/api")
{
v1.GET("/products", ListOfProducts)
v1.POST("/products/post",AddProduct)
}
Run Code Online (Sandbox Code Playgroud)
因此,您可以发送末尾不带正斜杠的请求:)