amphp / http-server-router

A router for Amp's HTTP Server.
MIT License
37 stars 6 forks source link

Which is the best way to handle CORS preflight request with OPTIONS method? #12

Closed barbosa89 closed 4 months ago

barbosa89 commented 4 months ago

I am creating a small API with Amphp Server in a subdomain and the interface is in the main domain, the classic usage is:

frontend https://app.com

API https://api.app.com

The browser is sending a preflight request, GET + preflight, with the OPTIONS method, so the server responds NOT ALLOWED METHOD and the browser returns a CORS error.

I could send the pull request but before sending it I'm researching the best way to do it. Please, check the following PR #13 for a better context.

The idea in this code is handle CORS preflight request using a global middleware, so the question is: ¿Is it the best way? ¿could I send a pull request with an improved code but with same idea?. Thanks.

trowski commented 4 months ago

OPTIONS is a different HTTP verb, and as such a route should be provided to handle it. You would not want a handler expecting another verb to receive an OPTIONS request.

// $router is an instance of Amp\Http\Server\Router
$router->addRoute('OPTIONS', '/', new ClosureRequestHandler(
    fn () => new Response(HttpStatus::OK, ['Access-Control-Allow-Origin' => '*']),
));