mpen
mpen

Reputation: 283313

How to disable chunked encoding for JSON responses in Laravel?

I'm returning an array from a controller method in Laravel. Laravel interprets this to mean I want to send JSON, which is great, but it doesn't set the Content-Length and instead uses Transfer-Encoding: chunked.

My responses are tiny, so I don't want to chunk them. How can I disable chunked encoding + enable Content-Length?

I'm using nginx for the server, if relevant.

Upvotes: 3

Views: 4950

Answers (2)

dgpro
dgpro

Reputation: 366

The only solution that worked for me in Laravel (5.8) was to add a header do disable Content-Encoding. The problem is that Nginx (10) was configured to compress the output using gzip which adds Content-Encoding:gzip, Transfer-Encoding: chunked and removes Content-Length header. But by adding that header Nginx bypasses compression and won't make those changes to the header.

$headers = [
        "Content-Length" => strlen($responseJson),
        "Content-Encoding" => "disabled",
    ];

Upvotes: 1

Yu Yenkan
Yu Yenkan

Reputation: 765

My solution is adding content-length headers to the response, then chunked-transfer will be replaced

    $responseJson = json_encode($response);

    $headers = [
        "Content-Length" => strlen($responseJson),
    ];

    return response($responseJson, 200, $headers);

you can try it with postman


for JSON content, just add content type in headers

    $headers = [
        "Content-Length" => strlen($responseJson),
        "Content-Type" => "application/json",
    ];

Upvotes: -1

Related Questions