How to enable CORS in Laravel?

cyber8200 picture cyber8200 · Mar 25, 2019 · Viewed 19.9k times · Source

I am in Laravel 5.8 - I kept getting this CORS issue

I've tried

php artisan make:middleware Cors

Add these code

<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
  public function handle($request, Closure $next)
  {
    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’);
  }
}

restart my local Apache 2 sudo apachectl -k restart

Open up app/Http/Kernel.php - added this 1 line

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'admin' => \App\Http\Middleware\AdminMiddleware::class,
        'dev' => \App\Http\Middleware\DevMiddleware::class,
        'cors' => \App\Http\Middleware\Cors::class, <----- 
    ];

refresh the site, go to console, still see the same CORS issue

How would one go about and debug this further?

Answer

ArtemSky picture ArtemSky · Mar 25, 2019

Try laravel-cors package that allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration.