Problems with CORS in calls from React |
I am creating an app in React and I decided to use Codeigniter 4 as API endpoint, I created the CORS filter like this
PHP Code: public function before(RequestInterface $request, $arguments = null) If I make a call from React as Content-Type: text/plain, it works, if I make it as application/json, it doesn't work and I get CORS Missing Allow Origin message If I make a call in text/plain and also pass an Authentication, it no longer works even in text/plain and I always get the same error How can I fix?
I think I have found the solution to the problem.
Some requests may require a pre-flight, in my case, if the call is of type text/plain which apparently is considered "secure" the pre-flight is not performed and therefore everything works, the moment I step into the header also Authorization, or simply switch from text/plain to application/json, the pre-flight is required and therefore it must be managed in the method management, otherwise every other request is blocked with the CORS error. To fix this I modified the CORS filter part I found here, like this: PHP Code: public function before(RequestInterface $request, $arguments = null) At this point, however, the routes must also be managed From this PHP Code: $routes->post( 'utenti_interni/get_records', 'Api\Sezioni\Utenti_interni::get_records'); To this PHP Code: $routes->match(['post', 'options'], 'utenti_interni/get_records', 'Api\Sezioni\Utenti_interni::get_records'); This is how routes for OPTIONS and POST are handled This way everything works, both using text/plain and application/json and either sending the Authentication or not sending it If you have suggestions to optimize it even more, you are welcome
READ:
Cross Domain JSON Requests What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
|
Welcome Guest, Not a member yet? Register Sign In |