Laravel响应json在实际响应后添加空的大括号



我在一个不由路由直接调用的函数中发送一个 json 响应,所以我添加了这样的send()函数:

return response()->json([
'key' => 'value'
], 400)->send();

这会导致浏览器中出现以下响应:

{"key":"value"}{}

这些空的大括号从何而来?我怎样才能摆脱它们,因为这会导致前端无法识别真正的响应。

为了解决这个问题,简化的代码如下所示:

routes.php

Route::post('/validate', 'ValidationController@validate');

ValidationController.php

public function validate(Request $request) 
{
// Does some validation
$this->saveData($request);
}
private function saveData(Request $request)
{
// saves the data
try {
// Tries something
} catch (Throwable $exception) {
return response()->json([
'key' => 'value'
], 400)->send();
}
// saves the data
}

响应上的send()并不一定会阻止代码进一步运行。它只是将响应写入 OB。控制器中没有任何内容可以阻止进一步执行(如return(。事实上,它只在 FastCGI 环境中这样做,因为它在内部调用fastcgi_finish_request

如果您使用 Apache,您的问题很容易重现:

response(['test' => 'testdata'])->send();
return response()->json(null);
// --> {"test":"testdata"}{}

幸运的是,还有throwResponse()帮手。如果你使用它而不是send()它会抛出响应作为HttpResponseException,从而阻止进一步的代码执行(->写入 OB/output 的潜在额外响应(。


更多见解:

我只是猜测在您的控制器中您编写// saves the data最终您有某种返回null值的return

天真的解决方案是:

  • exitsend()之后 - 真的很丑
  • return对控制器的响应,检查方法的返回值,如instanceof Response并进一步返回

throwResponse真正有用/方便,而不是这样的解决方案。

response()会自动将对象和数组变形为json。您只需要执行以下操作:

return response([
'key' => 'value'
], 400)->send();

请参阅:https://github.com/laravel/framework/blob/5.2/src/Illuminate/Http/Response.php#L43

最新更新