在 Laravel 6 中,基于后置中间件统一处理 302 跳转后的请求查询参数丢失问题

1、在 Laravel 6 中,带查询参数的请求,在 302 跳转后,查询参数丢失。如图1

图1

2、原计划在具体的请求时,判断此查询参数是否存在,如果存在,则在 302 跳转后,自动带上。但是此方案,无法避免后续可能还存在着其他的请求也有类似的问题。最终决定,基于后置中间件统一处理 302 跳转后的请求查询参数丢失问题。

3、将新建的中间件放入 web 中间件组,因为其仅需要应用于 Web UI 。


    /**
     * The application's route middleware groups.
     *
     * @var array
     */    protected $middlewareGroups = [
        'web' => [
            // ...
            \App\Http\Middleware\ThemeEditorQueryParam::class,
        ]
    ];

4、在一个控制器方法中实现 重定向到命名路由

return redirect()->route('account_login');

5、基于 league/uri 添加查询参数,执行 composer require league/uri-components、composer require league/uri。可参考:在 PHP 7.4 中,针对 URI ,基于 league/uri 添加查询参数

6、中间件中的代码实现如下

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\RedirectResponse;
use League\Uri\Uri;
use League\Uri\UriModifier;

class ThemeEditorQueryParam
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // 当响应为重定向时,判断请求中是否存在请求参数:oseid
        if ($response instanceof RedirectResponse) {
            $oseid = $request->query('oseid'); // 主题编辑器的主题的预览(2.0)
            if (isset($oseid)) {
                $uri = Uri::createFromString($response->getTargetUrl());
                $editorUri = UriModifier::mergeQuery($uri, 'oseid=' . $oseid);
                $response->setTargetUrl($editorUri->jsonSerialize());
            }
        }

        return $response;
    }
}

7、打开网址:https://xxx.local/products/ri-yuan-ce-shi-bian-zhong?variant=656 ,不带 oseid 参数,302 跳转至:https://xxx.local/account/login 。符合预期。如图2

图2

8、打开网址:https://xxx.local/products/ri-yuan-ce-shi-bian-zhong?variant=656&oseid=6462e3db4cd20 ,有带 oseid 参数,302 跳转至:https://xxx.local/account/login?oseid=6462e3db4cd20 。符合预期。如图3

图3

永夜