首页 > 解决方案 > Lumen 5.8 启用 cors

问题描述

我正在尝试在由 React Js 前端调用的 Lumen 5.8 后端 api 系统中启用 CORS。

这是我所做的:

  1. 我在 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); });
    }
  }
}
  1. 然后我创建了 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;
    }
}
  1. 在 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()

我不想安装任何软件包,我已经尝试过但没有得到结果,我只想修复这个错误,因为我想它可能是有效的。请你帮助我好吗??

提前感谢您的回答。

标签: phplaravelcorslumen

解决方案


您的标题说 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 详细信息。


推荐阅读