gin-contrib / cors

Official CORS gin's middleware
https://gin-gonic.github.io/gin/
MIT License
1.79k stars 186 forks source link

Missing Access-Control-Allow-Origin in response header. #29

Open nickhsine opened 7 years ago

nickhsine commented 7 years ago

I use @1.2.0 version, and the response header lacks of Access-Control-Allow-Origin header.

However, if I upgrade to the latest commit, the problem will be solved. I am wondering when @1.3.0 will be released?

dangyanglim commented 6 years ago

i meet the same problem the response header lacks of Access-Control-Allow-Origin header cors do not work

can u tell me how to get the cors version and how to update

dangyanglim commented 6 years ago

still not work

dangyanglim commented 6 years ago

it work when i put

router := gin.Default() router.Use(cors.Default())

together

not split

nickhsine commented 6 years ago

@dangyanglim I use glide to control code dependencies. the following is how I set the pkg version in my glide.yaml

- package: github.com/gin-contrib/cors
  version: 567de191692713543513692ecba9f6ca08cd660a

567de191692713543513692ecba9f6ca08cd660a is the latest commit, and it works fine.

seblegall commented 6 years ago

Hi,

It seems I have the same issue. I'm working with dep.

I tried using the last commit and also the v1.2 tag.

It's working when using the example above :

router := gin.Default()
router.Use(cors.Default())
router.Run()

But then, I need to add a Authorization header. So the code is :

config := cors.DefaultConfig()
config.AllowAllOrigins = true
config.AllowCredentials = true
config.AddAllowHeaders("authorization")
router.Use(cors.New(config))
router.Run()

This is where I get the error from JavaScript : No 'Access-Control-Allow-Origin' header is present on the requested resource

Any idea?

nickhsine commented 6 years ago

@seblegall You may need to assign a newer commit when you install this package. I am installing this commit.

seblegall commented 6 years ago

Still not working...

nickhsine commented 6 years ago

For your reference, here is what I have coded

And I am using this commit 567de191692713543513692ecba9f6ca08cd660a

wangshao1 commented 6 years ago

Try this

router.Use(cors.New(cors.Config{
        AllowMethods:     []string{"GET", "POST", "OPTIONS", "PUT"},
        AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "User-Agent", "Referrer", "Host", "Token"},
        ExposeHeaders:    []string{"Content-Length"},
        AllowCredentials: true,
        AllowAllOrigins:  false,
        AllowOriginFunc:  func(origin string) bool { return true },
        MaxAge:           86400,
    }))
BenKnigge commented 6 years ago

I think that I may be experiencing this same issue Access-Control-Allow-Origin is missing from all GET requests when using cors.DefaultConfig()

Triple-Z commented 6 years ago

I have met the same issue when i use router.Use(cors.Default()) .

And I solved it by:

func CORS() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    }
}
SilentFlyBy commented 6 years ago

Had the same problem. Solved it by registering the middleware with router.Use(cors.Default()) BEFORE registering any routes

annagat commented 5 years ago

Just like SilentFlyBy, I have solve mine by registering the middleware with router.Use(cors.Default()) BEFORE registering any routes.

Sherlock-Holo commented 5 years ago

I see the codes, it seems applyCors function miss c.Next(), is it this problem?

trivigy commented 5 years ago

@Sherlock-Holo ran into the same issue and was looking for an answer for a while. Here is the answer. https://github.com/gin-gonic/gin/issues/287

vivektiwary commented 5 years ago

Nothing worked for me, at the end I had to configure nginx for cors.

snowdream commented 5 years ago

Still not working...

@Triple-Z Thank you ,It works well.

pluveto commented 4 years ago

Still not working. But @Triple-Z's method works

scottenock commented 4 years ago

Throwing my name into the hat.

I was experiencing the issue as I was providing gin with the cors middleware after I had defined my routes.

Hope that helps someone! ✌️

jeffpohlmeyer commented 4 years ago

I have met the same issue when i use router.Use(cors.Default()) .

And I solved it by:

func CORS() gin.HandlerFunc {
  return func(c *gin.Context) {
      c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
      c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
      c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
      c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

      if c.Request.Method == "OPTIONS" {
          c.AbortWithStatus(204)
          return
      }

      c.Next()
  }
}

Just wondering, where and how would this be applied? Surely not instead of using the cors package, right?

blue14753 commented 4 years ago

I have met the same issue when i use router.Use(cors.Default()) . And I solved it by:

func CORS() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    }
}

Just wondering, where and how would this be applied? Surely not instead of using the cors package, right?

try router.Use(CORS())

GoCoGit commented 4 years ago

Hi,

It seems I have the same issue. I'm working with dep.

I tried using the last commit and also the v1.2 tag.

It's working when using the example above :

router := gin.Default()
router.Use(cors.Default())
router.Run()

But then, I need to add a Authorization header. So the code is :

config := cors.DefaultConfig()
config.AllowAllOrigins = true
config.AllowCredentials = true
config.AddAllowHeaders("authorization")
router.Use(cors.New(config))
router.Run()

This is where I get the error from JavaScript : No 'Access-Control-Allow-Origin' header is present on the requested resource

Any idea?

Thank you so much!

mclxly commented 4 years ago
go 1.15

require (
    github.com/gin-contrib/cors v1.3.1
    github.com/gin-gonic/gin v1.6.3
)

After 6 hours... c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE") change to c.Writer.Header().Set("Access-Control-Allow-Headers", "*") c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH")

It works finally. Hope help somebody.

SparK-Cruz commented 3 years ago

I have met the same issue when i use router.Use(cors.Default()) .

And I solved it by:

func CORS() gin.HandlerFunc {
  return func(c *gin.Context) {
      c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
      c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
      c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
      c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

      if c.Request.Method == "OPTIONS" {
          c.AbortWithStatus(204)
          return
      }

      c.Next()
  }
}

Using this solution instead of the whole lib, thank you!

Elliot-Baxus commented 2 years ago

I have met the same issue when i use router.Use(cors.Default()) . And I solved it by:

func CORS() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    }
}

Using this solution instead of the whole lib, thank you!

Conceptually, what does the if statement in this method check for?

jayy-lmao commented 2 years ago

I have met the same issue when i use router.Use(cors.Default()) . And I solved it by:

func CORS() gin.HandlerFunc {
  return func(c *gin.Context) {
      c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
      c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
      c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
      c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

      if c.Request.Method == "OPTIONS" {
          c.AbortWithStatus(204)
          return
      }

      c.Next()
  }
}

Using this solution instead of the whole lib, thank you!

Conceptually, what does the if statement in this method check for?

Options is just used as a pre-flight check. We just want to OK it if it comes through

michealroberts commented 2 years ago

This is still not fixed for me ... seeing lots of errors in Chrome.

CaiqueCastro07 commented 2 years ago
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
        if c.Request.Method == "OPTIONS" {
            c.IndentedJSON(204, "")
            return
        }

        c.Next()
    }
}

    router.Use(CORS())

Only by sending c.IndentedJSON(204,"") I could make it work, the abortWithStatus will replace your headers set previously.

CaiqueCastro07 commented 2 years ago
return func(c *gin.Context) {
    c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
    c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
    c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
    c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
    if c.Request.Method == "OPTIONS" {
        c.IndentedJSON(204, "") 
        return
    }

    c.Next()
}

}

router.Use(CORS())
Cyberpunk314 commented 2 years ago

I think your request header must contain the "Origin" field, otherwise, it will not set "Access-Control-Allow-Origin"="*" in the response header.

image image image image
clarkmcc commented 2 years ago

I'm not sure why this has to be so finicky. I feel like I should be able to do this, but this is not working. This is obviously registering before the routes are registered since the routes are dependent on the existence of the v1 variable.

var app = gin.Default()
var v1 = app.Group("/api/v1", cors.Default())
XFrankly commented 2 years ago

this is work for one time, but if application restart, it will invalid, it will nedd : c.Header("Access-Control-Max-Age", 86400) and need build again after 86400 s why?

pricetula commented 1 year ago

https://github.com/gin-contrib/cors/issues/29#issuecomment-700662773 This one worked for me. Thank you bud

TheNotary commented 1 year ago

I fixed it with the router.Use(cors.Default()) trick (make sure it's using the github.com/gin-contrib/cors import, I think it defaults to a random dependency) but my browser cached the original response so it seemed like nothing was working. Here's the fix on the frontend:

let params = {
      method: 'get',
      cache: 'no-cache'
}

fetch(baseUrl + "/users/", params)
JakobMiksch commented 1 year ago

I fixed it by changing the route from projects.GET("/") to projects.GET("")

The additional slash / is apparently a problem.

l2D commented 11 months ago

I fixed it by changing the route from projects.GET("/") to projects.GET("")

The additional slash / is apparently a problem.

At the same point, I found the CORS problems with the correct configuration of gin-contrib/cors.

Behaviour:

    router := gin.Default()
    router.Use(cors.New(cors.Config{
        AllowOrigins:     []string{"http://localhost:3000"},
        AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
        AllowHeaders:     []string{"Origin", "Content-Type", "Content-Length", "Authorization"},
        AllowCredentials: true,
        MaxAge:           12 * time.Hour,
    }))

The issue occur because we added / (trailing slash) in our routes.

        r := c. Group ("/my-route")
        r.GET("/", myFunc.GetAll)
        r.POST("/", myFunc.Create)
        r.PUT("/", myFunc. Update)
        r.DELETE("/", myFunc. Delete)

we fixed by deleted /

        r := c. Group ("/my-route")
        r.GET("", myFunc.GetAll)
        r.POST("", myFunc.Create)
        r.PUT("", myFunc. Update)
        r.DELETE("", myFunc. Delete)
JiaHuann commented 2 months ago

It is strange....

FE: Access to fetch at 'http://localhost:8080/api/v1/xxxx' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

But I use:

    // r.Use(cors.New(cors.Config{
    //  AllowOrigins:     []string{"http://localhost:3000"},
    //  AllowMethods:     []string{"GET", "POST", "OPTIONS", "PUT"},
    //  AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "User-Agent", "Referrer", "Host", "Token","Authorization"},
    //  ExposeHeaders:    []string{"Content-Length"},
    //  AllowCredentials: true,
    // }))

i cant fix that

我在使用时遇到了同样的问题router.Use(cors.Default())。 我通过以下方式解决了它:

func CORS() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    }
}

使用这个解决方案而不是整个库,谢谢!

从概念上讲,这个方法中的if语句检查什么?

Options只是进行飞行前检查。我们只是想确认一切顺利

but this works good for me

just want to know why......