如何在Laravel中为JSON响应禁用分块编码? [英] How to disable chunked encoding for JSON responses in Laravel?

查看:145
本文介绍了如何在Laravel中为JSON响应禁用分块编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从Laravel中的控制器方法返回一个数组. Laravel将此解释为我想发送JSON,这很棒,但是它没有设置Content-Length而是使用了Transfer-Encoding: chunked.

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?

如果有的话,我正在为服务器使用nginx.

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

推荐答案

我的解决方案是在响应中添加content-length标头,然后将替换chunked-transfer

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

对于JSON内容,只需在标题中添加内容类型

for JSON content, just add content type in headers

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

这篇关于如何在Laravel中为JSON响应禁用分块编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆