Php Laravel为什么中间件没有';在某些API中不起作用

Php Laravel为什么中间件没有';在某些API中不起作用,php,laravel,Php,Laravel,我定义了两个中间件:EnableCORSRequest和EnableAllCORSRequestEnableCORSRequest是一个全局中间件,我已经将它加载到Kernel.php中 Kernel.php的部分代码 $protected $middleware = [ // ... other middleware EnableCORSRequest::class, ]; /** * The application's ro

我定义了两个中间件:
EnableCORSRequest
EnableAllCORSRequest
EnableCORSRequest
是一个全局中间件,我已经将它加载到
Kernel.php

Kernel.php的部分代码

    $protected $middleware = [
        // ... other middleware
        EnableCORSRequest::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            // ... some middleware, I don't use web.php
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
            'cors', // this is EnableCORSRequest
        ],

        'api_no_throttle' => [
            'bindings',
            'cors', // this is EnableCORSRequest
        ]
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        // ... others
        'cors' => EnableCORSRequest::class,
        'no_cors' => EnableAllCORSRequest::class,
    ];
我在
api.php
中使用它:

// I don't want this api to be blocked by cors, so use this middleware
Route::post('/merchant/wallet/withdraw', 'Wallet@withdraw')
    ->middleware('no_cors');
但是事实上,
没有错误,没有警告。
为了测试,我在这两个类中添加了日志消息

class EnableCORSRequest
{
    public function handle($request, Closure $next)
    {
        // add this const definition, because to avoid that if this middleware loaded after another one, the CORS option may be overwritten
        if(defined('ALLOW_CORS_REQUEST')){
            return $next($request);
        }

        \Log::info('enable_cors');

        // ......
    }
}



class EnableAllCORSRequest
{
    public function handle($request, Closure $next)
    {
        define('ALLOW_CORS_REQUEST', 1);

        \Log::info('disable_cors');

        $response = $next($request);

        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
        $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        $response->header('Access-Control-Allow-Credentials', 'true');

        return $response;
    }
}

然后我通过浏览器访问这个api,并查看我的日志文件,只需
[2020-05-27 15:13:36]test.INFO:启用\u cors

中间件一步一步地工作,这样第一个全局中间件就可以工作了
当应用程序转到EnableCORSRequest类时,它似乎总是不允许设置请求,因为它首先运行,所以你应该更改你的senario。

我会做一些测试,比如更改中间件的名称,看看是否有错误500。是的,但它在另一个日志中添加了日志,所以我应该看到
禁用的\u CORS
日志,但我没有