将自定义中间件添加到组

时间:2019-12-06 18:45:51

标签: laravel

在“ routes / api.php”中定义的路由应该使用“ api”中间件组。

但是,如果我添加了自定义中间件(此处为“ cors”),则不会触发该中间件。为什么呢:

    protected $middlewareGroups = [
        'web' => [
            ...
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
            'cors'
        ],
    ];

    protected $routeMiddleware = [
        'cors' => \App\Http\Middleware\Cors::class,
        ...
   ]

仅当我全局使用“ cors”时,它才有效:

protected $middleware = [
    \App\Http\Middleware\Cors::class
]

我只想与api组一起使用。

我的中间件:

<?php
namespace App\Http\Middleware;

use Closure;

class Cors
{
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header(
                'Access-Control-Allow-Origin',
                '*'
            )
            ->header(
                'Access-Control-Allow-Headers',
                'X-REQUESTED-WITH'
            );
    }
}

0 个答案:

没有答案