问题
This topic has been request Laravel - how to Prefix all json responses to protect against json injection
without any reply so I try again.
I've tried with
Route::filter('protectionJson',function($route,$request ,$response)
{
if($request->ajax() && ($response instanceof \Illuminate\Http\JsonResponse)){
return ")]}',\n".json_encode($response->getData());
}
});
Route::get('user', array('as' => 'base.user.index', 'uses' => 'App\Controllers\UserController@index'))->before('hasAccess:users')->after('protectionJson');
and
App::after(function($request, $response)
{
if($request->ajax() && ($response instanceof \Illuminate\Http\JsonResponse)){
return ")]}',\n".json_encode($response->getData());
}
});
but it doesn't work I mean I've got always the standar json format.
回答1:
If you want to prepend/append data to the response you can access the response data using the response objects getContent()
method.
Route::filter('json.protect',function($route,$request,$response = null)
{
if($response instanceof \Illuminate\Http\JsonResponse) {
$json = ")]}',\n" . $response->getContent();
return $response->setContent($json);
}
});
You can then attach this to the route using the after
property.
Route::get('/test', array('after' =>'json.protect', function()
{
$test = array(
"foo" => "bar",
"bar" => "foo",
);
return Response::json($test);
}));
Alternatively, if you don't want to attach a filter to each route, then it is also possible to utilize the App::after
hook
App::after(function($request, $response)
{
if($response instanceof \Illuminate\Http\JsonResponse) {
$json = ")]}',\n" . $response->getContent();
return $response->setContent($json);
}
});
来源:https://stackoverflow.com/questions/24538305/laravel-how-to-prefix-all-json-responses-to-protect-against-json-injection