Reputation: 45
I am having trouble to create web app using Angular which is accessing to RESTful API built by Laravel. Although I have created middleware which passes correct headers, it does not work.
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Credentials', 'true')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Auth-Token, Origin, Authorization');
}
}
Any one can help me?
Upvotes: 4
Views: 2983
Reputation: 3189
Well, this is a kind of annoying issue, I know, but there are 2 solutions.
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;}]);
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.
Upvotes: 5