Lumen 5.8 启用 CORS 的正确姿势

Lumen 5.8 启用 CORS 的正确姿势

本文旨在帮助开发者在 Lumen 5.8 框架中正确启用跨域资源共享(CORS),解决常见的 middleware() 方法未定义错误。文章将深入探讨 Lumen 和 laravel 的 IOC 容器差异,并提供手动配置 CORS 中间件的步骤,同时推荐使用成熟的 CORS 包以简化配置过程,从而实现前后端分离架构下安全可靠的跨域访问。

问题根源:Lumen 与 Laravel 的 IOC 容器差异

在尝试手动配置 CORS 中间件时,出现 Call to undefined method IlluminateFoundationApplication::middleware() 错误,其根本原因在于 Lumen 和 Laravel 使用了不同的 IOC 容器。Laravel 使用 IlluminateFoundationApplication,而 Lumen 使用 LaravelLumenApplication。前者没有 middleware() 方法,导致注册中间件失败。

手动配置 CORS 中间件 (不推荐)

尽管不推荐,以下是手动配置 CORS 中间件的步骤,但请注意,这可能无法完全覆盖所有 CORS 场景,且容易出错:

  1. 创建 CatchAllOptionsRequestsProvider.php

    在 app/Providers 目录下创建该文件,用于处理 OPTIONS 请求。

    <?php  namespace AppProviders;  use IlluminateSupportServiceProvider;  class CatchAllOptionsRequestsProvider extends ServiceProvider {     public function register()     {         $request = app('request');         if ($request->isMethod('OPTIONS')) {             app()->options($request->path(), function () {                 return response('', 200);             });         }     } }
  2. 创建 CorsMiddleware.php:

    在 app/http/Middleware 目录下创建该文件,用于设置 CORS 头部。

    <?php  namespace AppHttpMiddleware;  use Closure;  class CorsMiddleware {     public function handle($request, Closure $next)     {         //Intercepts OPTIONS requests         if($request->isMethod('OPTIONS')) {             $response = response('', 200);         } else {             // Pass the request to the next middleware             $response = $next($request);         }          // Adds headers to the response         $response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');         $response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));         $response->header('Access-Control-Allow-Origin', '*');          // Sends it         return $response;     } }
  3. 修改 bootstrap/app.php:

    关键在于使用 Lumen 的 $app 实例注册中间件。在 Lumen 中,应该使用 $app->routeMiddleware() 来注册中间件。 修改后的 bootstrap/app.php 应该如下:

    $app->routeMiddleware([     'cors' => AppHttpMiddlewareCorsMiddleware::class ]);  $app->register(AppProvidersCatchAllOptionsRequestsProvider::class);

    注意: 此方法需要在路由中使用中间件,例如:$app->get(‘/api/data’, [‘middleware’ => ‘cors’, ‘uses’ => ‘ApiController@getData’]);

推荐方案:使用 CORS 包

强烈建议使用现成的 CORS 包,它们经过充分测试,配置简单,且能处理各种复杂的 CORS 场景。以下是两个推荐的包:

  • fruitcake/laravel-cors: Laravel 7.0 及更高版本默认包含的 CORS 包,也支持 Lumen。

    安装:

    composer require fruitcake/laravel-cors

    配置:

    在 bootstrap/app.php 中注册中间件:

    $app->middleware([     FruitcakeCorsHandleCors::class ]);

    该包提供了丰富的配置选项,可以在 config/cors.php 文件中进行自定义,例如允许的域名、请求方法、头部等。

  • spatie/laravel-cors: 另一个流行的 CORS 包,虽然已被存档,但仍适用于旧版本的 Lumen。安装和配置方式与 fruitcake/laravel-cors 类似。

总结:

手动配置 CORS 中间件容易出错,且难以覆盖所有情况。使用 fruitcake/laravel-cors 等成熟的 CORS 包是更可靠、更便捷的选择。通过简单的安装和配置,即可轻松实现 CORS,确保前后端分离架构下的安全通信。请务必根据项目需求选择合适的配置,例如限制允许的域名,以提高安全性。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享