首頁  >  文章  >  後端開發  >  為什麼在 CakePHP 3.4 中回顯自訂 HTTP 正文內容會導致「無法發出標頭」錯誤?

為什麼在 CakePHP 3.4 中回顯自訂 HTTP 正文內容會導致「無法發出標頭」錯誤?

Patricia Arquette
Patricia Arquette原創
2024-10-28 19:59:02687瀏覽

Why Does Echoing Custom HTTP Body Contents in CakePHP 3.4 Cause

在CakePHP 3.4 中,為什麼回顯自訂HTTP 正文內容會導致「無法發出標頭」錯誤

在CakePHP 3.4 中,回顯自訂HTTP 正文控制器方法中的內容可能會導致「無法發出標頭」錯誤。這是因為,從 3.4 開始,會明確檢查來自控制器的回顯資料是否有發送的標頭,如果發現任何標頭,則會觸發錯誤。

為什麼會發生此更改?

在 CakePHP 的早期版本中,允許在控制器中回顯資料。但是,這種做法可能會導致問題,包括:

  • 測試環境中無法辨識資料
  • 標頭無法傳送
  • 資料被切斷

為了解決這些問題,CakePHP 現在要求在發送自訂輸出時正確配置回應物件或使用序列化視圖。

發送自定義輸出的正確方法

配置響應

使用PSR-7 兼容接口:

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

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

return $this->response;</code>

使用已棄用的介面:

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

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

return $this->response;</code>

使用Response::getBody:

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

$this->response->getBody()->write($content);
return $this->response;</code>

使用序列化視圖

<code class="php">$content = ['method' => __METHOD__, 'class' => get_called_class()];

$this->set('content', $content);
$this->set('_serialize', 'content');</code>
使用序列化視圖

此方法需要請求處理程序元件和正確的URL 配置或請求中的application/json Accept 標頭。

結論

透過使用指定的方法而不是回顯數據,可以確保發送自訂HTTP 正文內容沒有錯誤,並且遵循CakePHP 的約定,從而產生更可靠和可維護的應用程式。

以上是為什麼在 CakePHP 3.4 中回顯自訂 HTTP 正文內容會導致「無法發出標頭」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn