sinusGob
sinusGob

Reputation: 4313

Cors doesnt work on gin and golang group routes

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

Upvotes: 8

Views: 10337

Answers (3)

Lavanya
Lavanya

Reputation: 11

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

Upvotes: 1

Andy Silver
Andy Silver

Reputation: 46

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

Upvotes: 3

Carlos Martinez
Carlos Martinez

Reputation: 4510

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

Upvotes: 13

Related Questions