## 請求主體
Every HTTP request has a body. If you are building a Slim application that consumes JSON or XML data, you can use the PSR-7 Request object’s`getParsedBody()`method to parse the HTTP request body into a native PHP format. Note that body parsing differs from one PSR-7 implementation to another.
> 每個HTTP請求都有一個主體。如果您正在構建一個使用JSON或XML數據的slim應用程序,那么可以使用PSR-7請求對象的`getParsedBody()`方法將HTTP請求體解析為原生PHP格式。注意,不同的PSR-7實現之間的主體解析是不同的。
You may need to implement middleware in order to parse the incoming input depending on the PSR-7 implementation you have installed. Here is an example for parsing incoming`JSON`input:
> 您可能需要實現中間件,以便根據安裝的PSR-7實現來解析輸入。下面是一個解析傳入`JSON`輸入的例子:
~~~php
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
class JsonBodyParserMiddleware implements MiddlewareInterface
{
public function process(Request $request, RequestHandler $handler): Response
{
$contentType = $request->getHeaderLine('Content-Type');
if (strstr($contentType, 'application/json')) {
$contents = json_decode(file_get_contents('php://input'), true);
if (json_last_error() === JSON_ERROR_NONE) {
$request = $request->withParsedBody($contents);
}
}
return $handler->handle($request);
}
}
~~~
~~~php
$parsedBody = $request->getParsedBody();
~~~
Figure 9: Parse HTTP request body into native PHP format
Technically speaking, the PSR-7 Request object represents the HTTP request body as an instance of`Psr\Http\Message\StreamInterface`. You can get the HTTP request body`StreamInterface`instance with the PSR-7 Request object’s`getBody()`method. The`getBody()`method is preferable if the incoming HTTP request size is unknown or too large for available memory.
> 從技術上講,Psr -7請求對象將HTTP請求體表示為`Psr\ HTTP \Message\StreamInterface`的一個實例。您可以使用PSR-7請求對象的`getBody()`方法獲得HTTP請求體`StreamInterface`實例。如果傳入的HTTP請求大小未知或者對于可用內存來說太大,則使用`getBody()`方法更好。
~~~php
$body = $request->getBody();
~~~
Figure 10: Get HTTP request body
The resultant`Psr\Http\Message\StreamInterface`instance provides the following methods to read and iterate its underlying PHP`resource`.
> 由此產生的`Psr\Http\Message\StreamInterface`實例提供了以下方法來讀取和迭代它的底層PHP`資源`。
* getSize()
* tell()
* eof()
* isSeekable()
* seek()
* rewind()
* isWritable()
* write($string)
* isReadable()
* read($length)
* getContents()
* getMetadata($key = null)
- 開始
- 安裝
- 升級指南
- Web服務器
- 概念
- 生命周期
- PSR 7
- 中間件
- 依賴容器
- 實例 及通知和警告處理
- Request
- 請求方法
- 請求頭信息
- 請求主體
- 上傳的文件
- 請求幫助
- 路由對象
- Response
- 響應狀態
- 響應標頭
- 響應體
- 返回JSON
- 視圖模板
- 路由
- 創建路由
- 路由回調
- 路由策略
- 路線占位符
- 路由名
- 路由組
- 路由中間件
- 路由表達式緩存
- 容器識別解析
- 封裝中間件
- 路由的中間件
- 錯誤處理中間件
- 方法重寫的中間件
- 輸出緩沖中間件
- 內容長度中間件
- 擴展功能
- 以 / 結尾的路由模式
- 獲取當前路由
- 設置CORS
- 使用POST表單上傳文件
- 第三方組件
- slim-session
- auth
- slim-api-skeleton
- dir