Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
fedulovivan opened this issue Oct 3, 2024 · 0 comments

Comments

@fedulovivan
Copy link

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant