CORS issue for Angular + Laravel project

I'm having trouble building a web application using Angular, accessed by the RESTful API created by Laravel. Although I created middleware that passes the 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');
    }
}

Can anybody help me?

+4
source share
1 answer

Well, this is some kind of unpleasant problem, I know, but there are 2 solutions.

1.

You define the OPTIONS method for each API call route and pass it the middleware that you created, as shown below:

Route::options('todos/{any?}', ['middleware' => 'cors', function(){return;}]);
Route::options('projects/{any?}', ['middleware' => 'cors', function(){return;}]);

2

You will crack the Laravel core class file so that it skips the CORS header for each OPTIONS request.

in

/vendor/laravel/framework/src/framework/Illuminate/Routing/RouteCollection.php

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);
    }

, CORS OPTIONS

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);
    }

, . . №2 - - Laravel, , Laravel? .: D

, .

+5

Source: https://habr.com/ru/post/1614413/


All Articles