>[danger] 該組件為系統組件,在組件樹中只可命名為 response ,不可修改為其他名稱。
## 響應
響應組件用來將控制器返回的數據、設置的HTTP報頭發送至客戶端。
| 類 | 調用 | 運行環境 |
| --- | --- | --- |
| Mix\Http\Message\Response\HttpResponse | app()->response | mix-httpd |
| Mix\Http\Message\Response\Compatible\HttpResponse | app()->response | Apache/PHP-FPM |
## 依賴注入配置
[>> 到 GitHub 查看默認配置 <<](https://github.com/mix-php/mix/blob/v2/applications/http/config/main_coroutine.php#L184)
參數 `defaultFormat` 全部常量明細:
- Mix\Http\Message\Response\HttpResponse::FORMAT_HTML
- Mix\Http\Message\Response\HttpResponse::FORMAT_JSON
- Mix\Http\Message\Response\HttpResponse::FORMAT_JSONP
- Mix\Http\Message\Response\HttpResponse::FORMAT_XML
## 設置響應格式
當開發API接口時,通常需要響應 `JSON`、`JSONP`、`XML` 格式,這時可在控制中指定響應格式,代碼如下:
~~~
public function actionIndex()
{
app()->response->format = \Mix\Http\Message\Response\HttpResponse::FORMAT_JSON;
return ['errcode' => 0, 'errmsg' => 'ok'];
}
~~~
也可以在App配置文件中的 `defaultFormat` 字段中定義默認的響應格式:
~~~
// 默認輸出格式
'defaultFormat' => Mix\Http\Message\Response\HttpResponse::FORMAT_JSON,
~~~
## 重定向
重定向到首頁。
~~~
app()->response->redirect('/');
~~~
## 設置狀態碼
~~~
// 方法1
app()->response->statusCode = 404;
// 方法2
app()->response->setStatusCode(404);
~~~
## 設置響應格式
~~~
// 方法1
app()->response->format = \Mix\Http\Message\Response\HttpResponse::FORMAT_JSON;
// 方法2
app()->response->setFormat(\Mix\Http\Message\Response\HttpResponse::FORMAT_JSON);
~~~
## 設置響應內容
~~~
// 方法1
app()->response->content = '<html>...</html>';
// 方法2
app()->response->setContent('<html>...</html>');
~~~
## 設置報頭
~~~
// 設置單個
app()->response->setHeader('Content-Type', 'application/json;charset=utf-8');
// 設置全部
app()->response->setHeaders(['Content-Type' => 'application/json;charset=utf-8']);
~~~
## 設置 `Cookie`
~~~
app()->response->setCookie($name, $value, $expires, $path, $domain, $secure, $httpOnly);
~~~
- 歡迎使用 MixPHP
- 安裝說明
- 全量安裝
- Phar 命令行
- 入門須知
- 增改應用
- 命名空間
- 自動加載
- 入口文件
- 配置文件
- 服務開發
- 核心基礎
- Bean
- Component
- Application
- 命令行
- 簡介
- 命令行開發常識
- 命令行開發
- 創建命令
- 命令參數
- 打印與顏色
- 控制臺程序
- 守護程序
- HTTP 服務
- 簡介
- 服務器
- 路由
- 請求
- 響應
- 控制器
- 視圖
- Auth
- Session
- 文件上傳
- 其他組件
- 分頁
- 驗證碼
- 圖片處理
- 客戶端
- GuzzleHttp
- 雜項
- Apache/PHP-FPM部署
- 調試與錯誤
- 安全建議
- WebSocket 服務
- 簡介
- 服務器
- 注冊器
- 連接
- 客戶端
- 測試
- 雜項
- nginx代理
- 60s無消息斷線
- TCP 服務
- 簡介
- 服務器
- 客戶端
- 測試
- UDP 服務
- 簡介
- 服務器
- 客戶端
- 測試
- 協程
- 簡介
- 開啟協程
- PHP Stream Hook
- xgo + Channel
- WaitGroup + xdefer
- 連接池
- 協程池
- 定時器
- 公共組件
- 中間件
- 驗證器
- 驗證器定義
- 驗證規則
- 靜態調用
- 模型
- 日志
- 緩存
- 數據庫
- Database
- QueryBuilder
- PDOConnection
- Persistent\PDOConnection
- Coroutine\PDOConnection
- MasterSlave\PDOConnection
- ExecuteListener
- Redis
- RedisConnection
- Persistent\RedisConnection
- Coroutine\RedisConnection
- ExecuteListener
- 常見問題
- 同一臺服務器部署多個服務
- 連接多個數據庫
- 如何設置跨域
- form-data 上傳文件失敗
- 開發工具
- 版本更新
- 不兼容改動
- 升級指南
- 文檔歷史