为什么我在状态码 204 时得到 "Invalid JSON"?

Why do I get a "Invalid JSON" when Status Code 204?

不知道是不是故意的。但是当我在我的控制器中使用响应代码 204 时,我在 PHPunit 中得到 "Invalid JSON was returned from the route"。

但是如果我将响应代码更改为 201,一切正常...为什么?

protected function output($title, $status = 201)
{
    return response([
        'title' => $title,
        'offers' => $this->popular,
    ], $status);
}

$this->output('Empty', 204); //Here is the error

在我的测试中

/** @test */
public function popular_can_fetch_food_lists() {
    $result = $this->json('post', route('popular', [
        'type' => $this->food->type,
        'id' => $this->food->id
    ]))->json();
}

如果你看一下 https://httpstatuses.com/204 你可以读到:

A 204 response is terminated by the first empty line after the header fields because it cannot contain a message body.

因此,如果您对任何内容使用 204,实际上将不会响应任何内容。

所以你不应该 运行 ->json() 在你的测试中。您应该只验证状态代码是否为 204