ozzo-routing icon indicating copy to clipboard operation
ozzo-routing copied to clipboard

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

Open fedulovivan opened this issue 4 months ago • 0 comments

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

fedulovivan avatar Oct 03 '24 11:10 fedulovivan