contributte / apitte

:wrench: An opinionated and enjoyable API framework based on Nette Framework. Supporting content negotiation, debugging, middlewares, attributes, annotations and loving openapi/swagger.
https://contributte.org/packages/contributte/apitte/
MIT License
61 stars 36 forks source link

@AllowOptionsMethod annotation to handle OPTIONS when using CORS #16

Closed artemevsin closed 6 years ago

artemevsin commented 6 years ago

Hi, my current use case: JS app sends POST request and axios sends preflight OPTIONS request. So I have to annotate every class method, that handles POST with @Method({"POST", "OPTIONS"}) and in case it's OPTIONS request I send empty response like that:

    /**
     * @Path("/")
     * @Method({"POST", "OPTIONS"})
     */
    public function create(ApiRequest $request, ApiResponse $response)
    {
        if ($request->getMethod() === 'OPTIONS') {
            return $response;
        }
    }

I can imagine, that not all requests should be handled with CORS (not really sure, if there is any real use case), so it can be usefull to use @AllowOptionsMethod annotation that will send response to these requests automatically.

What do you think about it?

f3l1x commented 6 years ago

Hi, interesting idea. The OPTIONS request is just for sure, it's allowed, right?

It would be better to handle it for all endpoints in different layer, instead of @AllowOptionsMethod annotation. Because, it's the same as your conditions, but you know, in annotations. ;-)

f3l1x commented 6 years ago

Fastest way ATM:

  1. Keep conditions. (break DRY)
  2. Prepend AllowOptionsMethodMiddleware (quite good). For all options methods.
artemevsin commented 6 years ago

I've been thinking about middleware and it will be good enough for my purpose. I'm too lazy to write conditions :smile:

Thank you for great job! :+1:

f3l1x commented 6 years ago

;-)

martenb commented 4 years ago

@f3l1x

what if OPTIONS methods were generated automatically?