php - 如何使用 CakePHP 3.4 输出自定义 HTTP 正文内容?回显导致 "Unable to emit headers"错误

标签 php cakephp httpresponse cakephp-3.x cakephp-3.4

使用 CakePHP 3.4、PHP 7.0。

我正在尝试做一个非常简单的 Controller 方法来输出一些 JSON。它正在输出“无法修改 header ...”。

public function test() {
    $this->autoRender = false;
    echo json_encode(['method' => __METHOD__, 'class' => get_called_class()]);
}

浏览器输出

{"method":"App\\Controller\\SomeController::test", "class":"App\\Controller\\SomeController"}

Warning (512): Unable to emit headers. Headers sent in file=...
Warning (2): Cannot modify header information - headers already sent by (output started at ...)
Warning (2): Cannot modify header information - headers already sent by (output started at ...)

我完全理解为什么 PHP 会提示这个。问题是为什么 CakePHP 会报错,我该怎么办?

需要注意的是 CakePHP 2.x 允许这样做。

最佳答案

Controller 不应该回显数据!回显数据会导致各种问题,从数据在测试环境中无法识别,到无法发送 header ,甚至数据被截断。

这样做在 CakePHP 2.x 中已经是错误的,尽管它可能在某些甚至大多数情况下都有效。随着新 HTTP 堆栈的引入,CakePHP 现在在回显响应之前明确检查已发送的 header ,并将相应地触发错误。

发送自定义输出的正确方法是配置并返回响应对象,或者使用序列化 View ,在 3.x 中仍然相同。

引用自文档:

Controller actions generally use Controller::set() to create a context that View uses to render the view layer. Because of the conventions that CakePHP uses, you don’t need to create and render the view manually. Instead, once a controller action has completed, CakePHP will handle rendering and delivering the View.

If for some reason you’d like to skip the default behavior, you can return a Cake\Network\Response object from the action with the fully created response.

* 从 3.4 开始,这将是 \Cake\Http\Response

Cookbook > Controllers > Controller Actions

配置响应

使用 PSR-7 兼容接口(interface)

$content = json_encode(['method' => __METHOD__, 'class' => get_called_class()]);

$this->response = $this->response->withStringBody($content);
$this->response = $this->response->withType('json');
// ...

return $this->response;

PSR-7 兼容接口(interface)使用不可变方法,因此利用了 withStringBody() 的返回值。和 withType() .在 CakePHP < 3.4.3 中,withStringBody()不可用,您可以直接写入正文流,这不会更改响应对象的状态:

$this->response->getBody()->write($content);

使用已弃用的接口(interface)

$content = json_encode(['method' => __METHOD__, 'class' => get_called_class()]);

$this->response->body($content);
$this->response->type('json');
// ...

return $this->response;

使用序列化 View

$content = ['method' => __METHOD__, 'class' => get_called_class()];

$this->set('content', $content);
$this->set('_serialize', 'content');

这还需要使用请求处理程序组件,并使用 .json 启用扩展解析和使用相应的 URLs附加,或使用 application/json 发送适当的请求接受 header 。

另见

关于php - 如何使用 CakePHP 3.4 输出自定义 HTTP 正文内容?回显导致 "Unable to emit headers"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42378793/

相关文章:

mysql - 如何通过 cakephp phinx 迁移迁移列类型 DOUBLE?

mysql - CakePHP 3 patchEntity SQL日期失败

php - 大文件解析导入 PHP MySQL

javascript - Asp.Net MVC 在响应期间合并和删除内联脚本

php - 使用 FPDF 将文件保存到预先指定的目录

php - 访问 GROUP_CONCAT 的单个记录

php - 从 2 个不同的表中选择但相关数据

HTTP 444(无响应)而不是 404、403 错误页面?

c# - WebAPI 返回文件和下载未开始

php - HTML5 中没有名称的输入有什么意义?