php – 在Laravel 5中间件中操纵JSON
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 在Laravel 5中间件中操纵JSON,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2006字,纯文字阅读大概需要3分钟。
内容图文
![php – 在Laravel 5中间件中操纵JSON](/upload/InfoBanner/zyjiaocheng/824/6b3036fecca34676b3f5787a26d08f62.jpg)
我有一个Ajax请求,发送到Laravel 5应用程序.
但是在将JSON发送给控制器之前,我需要重新格式化/更改/ … 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);
}
}
在您的控制器上获取json,而不是内容,或者您??将获得没有我们的过滤器的原始json:
public function index(Request $request)
{
//var_dump and die our filtered json
dd($request->json()->all());
}
内容总结
以上是互联网集市为您收集整理的php – 在Laravel 5中间件中操纵JSON全部内容,希望文章能够帮你解决php – 在Laravel 5中间件中操纵JSON所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。