Search code examples
phplaravelcorsbackendsingle-page-application

I can get the token but CORS error display in secure route


I want to integrate Laravel with Angular. I can get the token becouse I ad this in cors.php

'paths' => ['api/*', 'sanctum/csrf-cookie', **'oauth/*'**],

But any another secure route doesn't work (display CORS error). I tryued use middleware

        return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');

I registered that in Kernel.php and I added that in Kernel. Finally I added this middleware in my routing

Route::group(['middleware' => ['cors', 'json.response']], function () {
    Route::get('/user', 'UserController@user')->middleware(['auth:api']);
    
});

But all the time I have a cors error. Any Idea how can I solve this?

How solve the problem with cors?


Solution

  • Install fruitcake/laravel-cors

    composer require barryvdh/laravel-cors
    

    In config/app.php -> providers

    Barryvdh\Cors\ServiceProvider::class,
    

    Then in terminal

    php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
    

    And finally in app/Http/Kernel.php

    protected $middlewareGroups = [
        'web' => [
            // ...
            \Barryvdh\Cors\HandleCors::class,
        ],
    
        'api' => [
            // ...
            \Barryvdh\Cors\HandleCors::class,
        ],
    ];
    

    Or

    Upgrade to latest version of Laravel, which support cross-issue by framework itself