REST - Laravel 使用 body 将 POST 重定向到其他路由

REST - Laravel redirect POST with body to other route

我目前 re-writing 是一个有多个端点的 API。但是,出于遗留目的,需要有一个可用于访问所有其他端点的端点。我们应该重定向到哪个端点取决于随请求一起发送的自定义 action header。

示例:

输入:Header -> 动作 A 输出:重定向到路由 '/some/url' 'ControllerA@someAction'

输入:Header -> 动作 B 输出:重定向到路由 '/some/other/url' 'ControllerB@someOtherAction'

通常,我可以使用 redirect() 方法,但后来我失去了 POST 方法的 body。我声明的所有端点都是 POST 方法。

基本上,问题是如何正确地将 POST 重定向到另一条路线?

另请注意我不能使用:

App::call('App\Http\Controllers\PlanningController@addOrUpdate', ['request' => $request]);

因为我的方法使用自定义请求 class 来处理验证。我得到一个异常,告诉参数应该是我自定义的类型 class 并且给出了 Illuminate\Http\Request

我实际上已经找到了问题的答案。我已经创建了一个中间件,它将 re-create 基于在 header.

中找到的值的请求

这里是中间件的句柄函数(只在Laravel 5.2上测试过):

use Request;
use Route;
use Illuminate\Http\Response;

...

public function handle($request, Closure $next, $guard = null)
{
    // Get the header value
    $action = $request->header('action');

    // Find the route by the action name
    $route = Actions::getRouteByName(action); // This returns some route, i.e.: 'api/v1/some/url'

    // Perform the action
    $request = Request::create(route, 'POST', ['body' => $request->getContent()]);
    $response = Route::dispatch($request);

    return new Response($response->getContent(), $response->status(), ['Content-Type' => 'text/xml']); // the last param can be any headers you like
}

请注意,这可能会在您的项目中与其他中间件发生冲突。我已经禁用了其他中间件并为此创建了一个特殊的路由组。由于我们手动将调用重定向到另一条路由,因此无论如何都会调用该路由上的中间件。但是,您也可以在控制器函数中实现此代码,这样就不会出现中间件冲突的问题!