Laravel为什么中间件在某些API中不起作用

时间:2020-05-27 07:19:52

标签: php laravel

我定义了两个中间件:EnableCORSRequestEnableAllCORSRequestEnableCORSRequest是全局中间件,我已经将其加载到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');

但是实际上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: enable_cors

1 个答案:

答案 0 :(得分:1)

中间件一步一步地工作因此全球首个中间件开始工作 当应用程序转到EnableCORSRequest类时,它似乎总是设置ALLOW_CORS_REQUEST,因为它首先运行,所以您应该更改Senario。