bcosca / fatfree

A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!
2.66k stars 446 forks source link

CORS OPTIONS preflight 404 if not routed #1242

Closed riccardo2k13 closed 1 year ago

riccardo2k13 commented 2 years ago

I'm building an API rest app. I was having issues with CORS preflight fail. I am not using the $f3->map(). I am mapping every routes in a custom routes.ini

Reading the docs I thought I could not care about OPTIONS, but if I do not route the OPTIONS, it always triggers a 404.

CORS preflight fails

I must add a [OPTIONS /api/... = Ctr->preflight] to handle it, where the preflight method just contains an exit function. Then f3 does the rest of the job

immagine

ikkez commented 2 years ago

In order to make it work, you just have to have a route at /api/v1/login .. i.e. when you have defined a GET or POST route for it, the OPTIONS preflight is collecting the available http methods that are available, returning a Access-Control-Allow-Methods: OPTION,GET,POST header. This should work out of the box. 404 means that the router probably has not found a route for the resource the request is trying to access.

riccardo2k13 commented 2 years ago

Thanks for the reply. I had it. What you say is right, but if I specify the attribute [ajax]

Ex: POST /api/v1/login [ajax] = Api_Auth_Controller->login // this makes the OPTIONS fail

While, as you said: POST /api/v1/login = Api_Auth_Controller->login // this works

ikkez commented 2 years ago

Well then it's probably a bug with the ajax flag, which should be ignored in such a case

Joseffb commented 2 years ago

I Second to just use the POST /api/v1/login = Api_Auth_Controller->login method.

I also do this in my middle-ware router (your pre-flight?) to handle any custom headers

$this->fw->copy('HEADERS.Origin','CORS.Origin');
$this->fw->set('CORS.Origin','*');
$this->fw->set('CORS.headers',['token','content-type', 'x-property-id']);
riccardo2k13 commented 2 years ago

In fact I will remove the [ajax] specification. Thanks to all.

ikkez commented 1 year ago

fixed.