## 返回 JSON
In it’s simplest form, JSON data can be returned with a default 200 HTTP status code.
> 在其最簡單的形式中,可以使用默認的200 HTTP狀態碼返回JSON數據。
~~~php
$data = array('name' => 'Bob', 'age' => 40);
$payload = json_encode($data);
$response->getBody()->write($payload);
return $response
->withHeader('Content-Type', 'application/json');
~~~
Figure 15: Returning JSON with a 200 HTTP status code.
We can also return JSON data with a custom HTTP status code.
> 我們還可以使用定制的HTTP狀態碼返回JSON數據。
~~~php
$data = array('name' => 'Rob', 'age' => 40);
$payload = json_encode($data);
$response->getBody()->write($payload);
return $response
->withHeader('Content-Type', 'application/json')
->withStatus(201);
~~~
Figure 16: Returning JSON with a 201 HTTP status code.
**Reminder**
The Response object is immutable. This method returns a*copy*of the Response object that has a new Content-Type header.**This method is destructive**, and it*replaces*the existing Content-Type header.
> 提醒
> Response對象是不可變的。此方法返回具有新內容類型標頭的響應對象的*copy*。**這個方法是毀滅性的**,它`替換`了現有的內容類型頭。
## Returning a Redirect返回一個重定向
You can redirect the HTTP client by using the`Location`header.
> 您可以使用`Location`報頭重定向HTTP客戶端。
~~~php
return $response
->withHeader('Location', 'https://www.example.com')
->withStatus(302);
~~~
Figure 17: Returning a redirect to https://www.example.com
- 開始
- 安裝
- 升級指南
- Web服務器
- 概念
- 生命周期
- PSR 7
- 中間件
- 依賴容器
- 實例 及通知和警告處理
- Request
- 請求方法
- 請求頭信息
- 請求主體
- 上傳的文件
- 請求幫助
- 路由對象
- Response
- 響應狀態
- 響應標頭
- 響應體
- 返回JSON
- 視圖模板
- 路由
- 創建路由
- 路由回調
- 路由策略
- 路線占位符
- 路由名
- 路由組
- 路由中間件
- 路由表達式緩存
- 容器識別解析
- 封裝中間件
- 路由的中間件
- 錯誤處理中間件
- 方法重寫的中間件
- 輸出緩沖中間件
- 內容長度中間件
- 擴展功能
- 以 / 結尾的路由模式
- 獲取當前路由
- 設置CORS
- 使用POST表單上傳文件
- 第三方組件
- slim-session
- auth
- slim-api-skeleton
- dir