如何在 Laravel 中启用 CORS?

How to enable CORS in Laravel?

我在 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 问题

如何进一步调试它?

尝试 laravel-cors 包,它允许您使用 Laravel 中间件配置发送 Cross-Origin 资源共享 headers。

第一个解决方案

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

CORS middleware 中的 handle function:

 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');

希望有用!

在下面给你添加.htaccess(只添加到目标站点和源站点)

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$  [R=200,L]

希望它能节省一些人的时间,编码愉快!!!

由于Nov 10, 2020 Laravel为此添加了build-in配置,您可以在config/cors.php中找到它,请查看https://github.com/laravel/laravel/blob/9.x/config/cors.php