Cors doesnt work on gin and golang group routes
Asked Answered
F

3

7

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

Fancier answered 13/2, 2019 at 8:18 Comment(4)
What the output of command curl -H "Origin: http://localhost:8000" --verbose localhost:9000 ? Does the header Access-Control-Allow-Origin: * present?Accad
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: 18Fancier
What is the problem?Fancier
Thanks for helpingFancier
D
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 :)

Duodiode answered 16/2, 2019 at 0:25 Comment(2)
Wow , I can't believe I have wasted close to one hour on a trailing slashBearcat
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)Lalonde
P
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

Pitfall answered 7/10, 2021 at 0:4 Comment(1)
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.Bathelda
U
0
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()))
Unnerve answered 25/5, 2022 at 11:8 Comment(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.Horseweed

© 2022 - 2024 — McMap. All rights reserved.