Skip to content

cors.Handler with cors.AllowAll is not working for POST request when attached to the router group #69

@fedulovivan

Description

@fedulovivan

In my case REST endpoint has a separate namespace defined with the router.Group like so:

rootRouter := routing.New()
rootRouter.Use(
  slash.Remover(http.StatusMovedPermanently)
)
apiGroup := rootRouter.Group("/api")
apiGroup.Use(
  errorHandler,
  content.TypeNegotiator(content.JSON),
  cors.Handler(cors.AllowAll) // ok for GET but not working for POST (!)
)

in this case header "Access-Control-Allow-Methods: POST" does not emitted when browser sends preflight request. This causes typical cors error in browser console (added for the search engines):

Access to XMLHttpRequest at 'http://localhost:7070/api/devices/10012db92b' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

So the solution is moving cors.Handler to the upper rootRouter.Use:

rootRouter := routing.New()
rootRouter.Use(
  slash.Remover(http.StatusMovedPermanently),
  cors.Handler(cors.AllowAll) // now works for both GET and POST
)
// ...

P.S.
emitted headers could be checked with following curl command:

curl -I -X OPTIONS -H "Origin: http://localhost:5173" -H 'Access-Control-Request-Method: POST' http://localhost:7070/api

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions