如何在Laravel中对每个响应强制执行JSON响应? [英] How do you force a JSON response on every response in Laravel?
问题描述
我正在尝试使用Laravel Framework构建REST api,我想要一种方法来强制API始终以JSON响应,而不是像这样进行操作:
I'm trying to build a REST api using Laravel Framework, I want a way to force the API to always responed with JSON not by doing this manulaly like:
return Response::json($data);
换句话说,我希望每个响应都是JSON.有什么好方法吗?
In other words I want every response to be JSON. Is there a good way to do that?
更新:即使在未找到类似异常的情况下,响应也必须为JSON
Update: The response must be JSON even on exceptions like not found exception.
推荐答案
要在控制器中返回JSON
,只需return $data;
To return JSON
in the controller just return $data;
对于错误的JSON
响应,请转到app\Exceptions\Handler.php
文件并查看render
方法.
For a JSON
response on errors, go to app\Exceptions\Handler.php
file and look at the render
method.
您应该可以重新编写它,使其看起来像这样:
You should be able to re-write it to look something like this:
public function render($request, Exception $e)
{
// turn $e into an array.
// this is sending status code of 500
// get headers from $request.
return response()->json($e, 500);
}
但是,您必须决定如何处理$e
,因为它必须是array
.您还可以设置状态代码和标头数组.
However you will have to decide what to do with $e
, because it needs to be an array
. You can also set the status code and header array.
但是如果发生任何错误,它将返回JSON
响应.
But then on any error, it will return a JSON
response.
还应注意,您可以更改report
方法来处理laravel记录错误的方式.更多信息此处.
It's also good to note that you can change the report
method to handle how laravel logs the error as well. More info here.
这篇关于如何在Laravel中对每个响应强制执行JSON响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!