I try this specific code but it keep on giving me error in
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)
}
}
The error is
My frontend is written in Vue.js and running on localhost:8000
localhost and the server is running on localhost:9000
Ok, so I tried to replicate this and found that I was making the AJAX request wrong, probably you made the same mistake as I did:
With a similar configuration:
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()
}
This AJAX request will throw the CORS error you're getting:
$.get('http://localhost:8080/api').then(resp => {
console.log(resp);
});
But adding a "/" at the end will work:
$.get('http://localhost:8080/api/').then(resp => {
console.log(resp);
});
So in your case, try requesting the URL: http://localhost:9000/api/products/
(with a forward slash at the end)
Moreover, you could also modify your routes to look like this:
v1 := router.Group("/api")
{
v1.GET("/products", ListOfProducts)
v1.POST("/products/post",AddProduct)
}
So you can send the request without the forward slash at the end :)