如何在Laravel中启用CORS?

问题描述 投票:8回答:2

我在Laravel 5.8中-我一直收到这个CORS问题

“”

我已经尝试过

php artisan make:middleware Cors

添加这些代码

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

重新启动本地Apache 2 sudo apachectl -k restart

打开app/Http/Kernel.php-添加了这1行

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, <----- 
    ];

刷新站点,转到控制台,仍然看到相同的CORS问题

一个人将如何进行进一步调试?

php laravel laravel-5 cors laravel-5.8
2个回答
9
投票

尝试使用laravel-cors程序包,该程序包允许您使用Laravel中间件配置发送跨域资源共享标头。


2
投票

第一个解决方案

尝试将CORS中间件设置为全局中间件

handle function中的CORS middleware

 public function handle($request, Closure $next)
 {
  return $next($request)
   ->header('Access-Control-Allow-Origin', '*')
   ->header('Access-Control-Allow-Methods', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS')
   ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
 }

要全局添加此中间件,请转到App\Http\Kernel,并将此行添加到$middleware数组中:

\App\Http\Middleware\Cors::class,

第二解决方案>>

您也可以在bootstrap/app.php中添加此代码

header('Access-Control-Allow-Origin', '*');
header('Access-Control-Allow-Methods', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
header('Access-Control-Allow-Headers', 'Content-Type, Authorization');

希望它起作用!

© www.soinside.com 2019 - 2024. All rights reserved.