Problems with CORS in calls from React - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28) +--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30) +--- Thread: Problems with CORS in calls from React (/showthread.php?tid=87443) |
Problems with CORS in calls from React - serialkiller - 04-20-2023 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? RE: Problems with CORS in calls from React - serialkiller - 04-20-2023 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 RE: Problems with CORS in calls from React - InsiteFX - 04-20-2023 READ: Cross Domain JSON Requests |