该主题已被请求Laravel -如何为所有json响应添加前缀以防止json注入
没有任何回复,所以我再试一次。
我试过了
Route::filter('protectionJson',function($route,$request ,$response)
{
if($request->ajax() && ($response instanceof IlluminateHttpJsonResponse)){
return ")]}',n".json_encode($response->getData());
}
});
Route::get('user', array('as' => 'base.user.index', 'uses' => 'AppControllersUserController@index'))->before('hasAccess:users')->after('protectionJson');
和
App::after(function($request, $response)
{
if($request->ajax() && ($response instanceof IlluminateHttpJsonResponse)){
return ")]}',n".json_encode($response->getData());
}
});
但它不起作用,我的意思是我总是有标准的json格式
如果您想在响应中添加/附加数据,您可以使用响应对象getContent()
方法访问响应数据。
Route::filter('json.protect',function($route,$request,$response = null)
{
if($response instanceof IlluminateHttpJsonResponse) {
$json = ")]}',n" . $response->getContent();
return $response->setContent($json);
}
});
您可以使用after
属性将其附加到路由。
Route::get('/test', array('after' =>'json.protect', function()
{
$test = array(
"foo" => "bar",
"bar" => "foo",
);
return Response::json($test);
}));
或者,如果你不想为每条路由附加一个过滤器,那么也可以利用App::after
钩子
App::after(function($request, $response)
{
if($response instanceof IlluminateHttpJsonResponse) {
$json = ")]}',n" . $response->getContent();
return $response->setContent($json);
}
});