Laravel response json 在真实响应后添加空花括号

Laravel response json adds empty curly braces after real response

我在一个函数中发送一个 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
}

response() 会自动将对象和数组变形为 json。您只需要做:

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

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

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

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

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

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


更多见解:

我只是猜测在你的控制器中你写了 // saves the data 最后你有某种 return return 是一个 null 值。

天真的解决方案是:

  • exit 在你 send() 之后 - 真的很丑
  • return 对控制器的响应,检查 return 方法的值,例如 instanceof Response 和 return 进一步

throwResponse 确实 helpful/convenient 而不是这样的解决方案。