我有一个发送到 Laravel 5 应用程序的 Ajax 请求。 但是在将 JSON 发送到 Controller 之前,我需要重新格式化/更改/... JSON。
有没有办法在中间件中操作请求体(JSON)?
<?php namespace App\Http\Middleware;
use Closure;
class RequestManipulator {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->isJson())
{
$json = json_decode($request->getContent(), TRUE);
//manipulate the json and set it again to the the request
$manipulatedRequest = ....
$request = $manipulatedRequest;
}
\Log::info($request);
return $next($request);
}
}
最佳答案
是的,您可能有两种类型的中间件,一种在请求之前运行,一种在请求之后运行,您可以找到有关它的更多信息 here .
要创建负责的中间件,您可以使用以下命令生成一个:
php artisan make:middleware ProcessJsonMiddleware
然后在你的内核上用一个好记的名字注册它
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'process.json' => 'App\Http\Middleware\ProcessJsonMiddleware',
];
这个中间件只是一个例子,它删除数组的最后一个元素并根据请求替换它:
<?php namespace App\Http\Middleware;
use Closure;
use Tokenizer;
class ProcessJsonMiddleware {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->isJson())
{
//fetch your json data, instead of doing the way you were doing
$json_array = $request->json()->all();
//we have an array now let's remove the last element
$our_last_element = array_pop($json_array);
//now we replace our json data with our new json data without the last element
$request->json()->replace($json_array);
}
return $next($request);
}
}
在你的 Controller 上获取 json,而不是内容,否则你将得到没有我们过滤器的原始 json:
public function index(Request $request)
{
//var_dump and die our filtered json
dd($request->json()->all());
}
关于php - 在 Laravel 5 中间件中操作 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29797999/