laravel 路由中带有参数的中间件执行了两次

laravel middleware with parameter in route executed twice

我有这个非常简单的中间件

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Log;

    class CacheResponseMinify
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle(Request $request, Closure $next)
        {
            Log::debug('***********************************************************');
            Log::debug($request);
            return $next($request);
        }
    }

此中间件与路由和参数相关联:

    Route::get('/route/{page}', [App\Http\Controllers\MyController::class, 'page'])->middleware([ 'cacheResponseMinify']);

我在浏览器中输入这个URL:http://localhost:81/route/my_page

在日志中,第一次执行hte中间件显示一个空数组:

    [2022-03-01 14:38:48] local.DEBUG: array (
    )  

第二次执行显示一个数组,其中包含加载的 URL

中的数据
    [2022-03-01 14:38:51] local.DEBUG: array (
      'action_name' => 'Title_of_the_page',
      'idsite' => '0',
      'rec' => '1',
      'r' => '588131',
      'h' => '14',
      'm' => '38',
      's' => '50',
      'url' => 'http://localhost:81/route/my_page',
      '_id' => '746a68055b9493f2',
      '_idts' => '1646141931',
      '_idvc' => '1',
      '_idn' => '1',
      '_refts' => '0',
      '_viewts' => '1646141931',
      'send_image' => '1',
      'pdf' => '1',
      'qt' => '0',
      'realp' => '0',
      'wma' => '0',
      'dir' => '0',
      'fla' => '0',
      'java' => '0',
      'gears' => '0',
      'ag' => '0',
      'cookie' => '1',
      'res' => '1920x1080',
      'gt_ms' => '404',
      'pv_id' => 'iGGVy6',
    )  

如果路由是绝对的,没有参数

    Route::get('/route/my_page', [App\Http\Controllers\MyController::class, 'page'])->middleware([ 'cacheResponseMinify']);

中间件只执行一次

你知道为什么使用路由和参数,中间件会执行两次吗?

我最终找到了问题的根源。

对于每个页面,我都使用 Matomo 设置了统计监控。 有一个脚本 matomo.js 触发对 matomo.php?list_of_parameters.

的调用

通过查询http://localhost:81/route/my_page,matomo脚本调用了http://localhost:81/route/matomo.php?list_of_parameters

路线中,有: Route::get('/route/{page}'

http://localhost:81/route/my_page 和 http://localhost:81/route/matomo.php?list_of_parameters 都经过这条路线。

在controller中,my_page对应一个具体的view,OK,缓存是正确的。

另一方面,matomo.php?list_of_parameters 进入默认视图,即目录的主页

Laravel 和缓存因此表现完全正常:-)

错误在别处。

matomo.js 文件使用 matomo_appli.js 中定义的参数。

在文件 matomo_appli.js 中定义了 URL_MATOMO。 对于本地环境和开发环境,它是一个空字符串。

这就是为什么调用的统计信息 url 是 http://localhost:81/route/matomo.php?list_of_parameters

我将 URL_MATOMO 修改为 link 指向 http://localhost:81/matomo/

现在,matomo stat links 的格式为 http://localhost:81/matomo/matomo.php?list_of_parameters

因此,不再需要通过 Laravel 路由或计划外缓存。