2
votes

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

enter image description here

My frontend is written in Vue.js and running on localhost:8000 localhost and the server is running on localhost:9000

2
What the output of command curl -H "Origin: http://localhost:8000" --verbose localhost:9000 ? Does the header Access-Control-Allow-Origin: * present?Зелёный
Rebuilt URL to: localhost:9000/ * Trying ::1... * TCP_NODELAY set * Connected to localhost (::1) port 9000 (#0) > GET / HTTP/1.1 > Host: localhost:9000 > User-Agent: curl/7.54.0 > Accept: */* > Origin: http://localhost:8000 > < HTTP/1.1 404 Not Found < Access-Control-Allow-Origin: * < Content-Type: text/plain < Date: Wed, 13 Feb 2019 08:48:10 GMT < Content-Length: 18sinusGob
What is the problem?sinusGob
Thanks for helpingsinusGob

2 Answers

5
votes

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

0
votes
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,
}))

try this