CORS issue for Angular + Laravel project

后端 未结 1 1422
青春惊慌失措
青春惊慌失措 2021-01-03 08:47

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 d

相关标签:
1条回答
  • 2021-01-03 09:21

    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.

    0 讨论(0)
提交回复
热议问题