skip to Main Content

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?

2

Answers


  1. Try with default settings and then try to modify it if necessary.
    No need to add other middleware, cause cors.php has default configuration which introduced by Laravel Team from Laravel 7.

    Login or Signup to reply.
  2. Install fruitcake/laravel-cors

    composer require barryvdh/laravel-cors
    

    In config/app.php -> providers

    BarryvdhCorsServiceProvider::class,
    

    Then in terminal

    php artisan vendor:publish --provider="BarryvdhCorsServiceProvider"
    

    And finally in app/Http/Kernel.php

    protected $middlewareGroups = [
        'web' => [
            // ...
            BarryvdhCorsHandleCors::class,
        ],
    
        'api' => [
            // ...
            BarryvdhCorsHandleCors::class,
        ],
    ];
    

    Or

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search