Well, this is a kind of annoying issue, I know, but there are 2 solutions.
1.
You define OPTIONS method for every API calling route, and make it pass the middleware you created like following:
Route::options('todos/{any?}', ['middleware' => 'cors', function(){return;}]);
Route::options('projects/{any?}', ['middleware' => 'cors', function(){return;}]);
2
You hack Laravel core class file, so that it passes CORS header for every OPTIONS request.
in the
/vendor/laravel/framework/src/framework/Illuminate/Routing/RouteCollection.php
you will find following function
protected function getRouteForMethods($request, array $methods)
{
if ($request->method() == 'OPTIONS') {
return (new Route('OPTIONS', $request->path(), function () use ($methods) {
return new Response('', 200, ['Allow' => implode(',', $methods)]);
}))->bind($request);
}
$this->methodNotAllowed($methods);
}
Update this function to following, so that it will pass CORS headers for OPTIONS request
protected function getRouteForMethods($request, array $methods)
{
if ($request->method() == 'OPTIONS') {
return (new Route('OPTIONS', $request->path(), function () use ($methods) {
return new Response('', 200, [
'Allow' => implode(',', $methods),
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers' => 'X-Requested-With, Content-Type, X-Auth-Token, Origin, Authorization',
]);
}))->bind($request);
}
$this->methodNotAllowed($methods);
}
So for me, both solutions work okay. Choice is yours.
But solution #2 is something hack on Laravel core, you might have some issues if you upgrade Laravel itself? But at least it has less coding. :D
Hope these solutions will be helpful.