php - Lumen 5.8 启用 cors
问题描述
我正在尝试在由 React Js 前端调用的 Lumen 5.8 后端 api 系统中启用 CORS。
这是我所做的:
- 我在 App\Providers 文件夹中创建了 CatchAllOptionsRequestsProvider.php。
use Illuminate\Support\ServiceProvider;
/**
* If the incoming request is an OPTIONS request
* we will register a handler for the requested route
*/
class CatchAllOptionsRequestsProvider extends ServiceProvider {
public function register()
{
$request = app('request');
if ($request->isMethod('OPTIONS'))
{
app()->options($request->path(), function() { return response('', 200); });
}
}
}
- 然后我创建了 CorsMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
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;
}
}
- 在 bootstrap/app.php 我添加了这个:
$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);
$app->register(App\Providers\CatchAllOptionsRequestsProvider::class);
结果我在 bootstrap/app.php 文件中收到此错误: PHP 致命错误:未捕获的错误:调用 /bootstrap/app.php:44 中未定义的方法 Illuminate\Foundation\Application::middleware()
我不想安装任何软件包,我已经尝试过但没有得到结果,我只想修复这个错误,因为我想它可能是有效的。请你帮助我好吗??
提前感谢您的回答。
解决方案
您的标题说 Lumen,bootstrap/app.php
表示 Lumen,但您的错误说您的$app
变量是 的实例Illuminate\Foundation\Application
,这没有意义。
Illuminate\Foundation\Application
是 Laravel 中使用的 IOC 容器,而不是 Lumen。而且,正如您的错误所示,它没有middleware()
方法。
你的$app
变量应该Laravel\Lumen\Application
是 Lumen 的 IOC 容器的一个实例。这个容器确实有middleware()
你正在寻找的方法。
我知道你反对它,但我建议使用一个包来实现 CORS。
- fruitcake/laravel-cors - 这个包是 Laravel 7.0 中默认包含的包。它还支持流明。
- spatie/laravel-cors - 这是另一个支持 Lumen 的流行包。它在 Laravel 默认包含 CORS 时已存档,但仍可用于旧版本。
这两个软件包都有安装和配置的详细说明,并将为您处理所有 CORS 详细信息。
推荐阅读
- kotlin - ArrayIndexOutOfBoundsException 分配给 charArrayOf()
- lazy-loading - 无法绑定到“ngIf”,因为它不是“gridster-item”的已知属性
- javascript - 遍历数组数组中的每个对象找到 id,将其与数组中的另一个对象匹配并将它们连接在一起
- c# - 由于文件不存在,Sharp SVN 更新崩溃
- c# - Rabbitmq - V6.0.0 - 无法加载类型“RabbitMQ.Client.NetworkConnection”
- c# - 带有重试策略的单元测试抛出异常
- vmware - 如何解决Ubuntu上的Ros安装错误
- awk - 使用 #SBATCH 向多个文件 (900+) 添加一列
- css - React 和 SCSS 从 scss 导出一个变量以进行反应
- node.js - npx create-react-app my-app 命令出错