如何在 Laravel 中启用 CORS?

新手上路,请多包涵

我在 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 添加了这一行

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

如何进一步调试呢?

原文由 code-8 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 929
2 个回答

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

原文由 ArtemSky 发布,翻译遵循 CC BY-SA 4.0 许可协议

第一个解决方案

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

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

希望它有效!

原文由 Behzad Pournouri 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏