Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

php - How to enable CORS in Laravel?

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 AppHttpMiddleware;
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' => IlluminateAuthMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'admin' => AppHttpMiddlewareAdminMiddleware::class,
        'dev' => AppHttpMiddlewareDevMiddleware::class,
        'cors' => AppHttpMiddlewareCors::class, <----- 
    ];

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

How would one go about and debug this further?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...