4

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

sinusGob
  • 4,053
  • 12
  • 46
  • 82
  • What the output of command `curl -H "Origin: http://localhost:8000" --verbose localhost:9000` ? Does the header `Access-Control-Allow-Origin: *` present? – Roman Kiselenko Feb 13 '19 at 08:46
  • ```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: 18``` – sinusGob Feb 13 '19 at 08:49
  • What is the problem? – sinusGob Feb 13 '19 at 08:49
  • Thanks for helping – sinusGob Feb 13 '19 at 08:49

3 Answers3

12

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

Carlos Martinez
  • 4,350
  • 5
  • 32
  • 62
  • 4
    Wow , I can't believe I have wasted close to one hour on a trailing slash – Cozy Dec 10 '20 at 09:44
  • Thank you, this was helpful. when having an URI Parameter binding, the route should look like this: `v1.GET("/products/:id/", ListOfProducts)` or `v1.GET("/products/something/:id/", ListOfProducts)` – maes Mar 22 '22 at 22:39
2
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

  • This really helped me out, thanks! `router.Use(cors.Default())` worked at first, but when I started using `Authentication: Bearer...` headers in my frontend, it stopped working because that makes browsers send `OPTIONS` methods to the backend for preflight checking and the defaults don't handle options requests or Authentication headers. – Ninjaxor Jan 23 '23 at 21:58
0
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
}

In func main add:

r = gin.Default()

r.Use(cors.New(CORSConfig()))

Lavanya
  • 1
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 25 '22 at 11:53