簡體   English   中英

使用 Slim v4.1 請求參數為空

[英]Request parameters are empty using Slim v4.1

我將Slim v4用於一些 arduino 組件 API。 當我通過我的控制器進行POST調用時,我得到一個空的請求正文,沒有我發送給它的參數。

在下面的代碼中,在$parameters變量中我有一個 NULL。

public function __invoke(
    ServerRequestInterface $request,
    ResponseInterface $response
) : ResponseInterface {
    $ret = [
        'success'   => false
    ];

    $parameters = (array) $request->getParsedBody();
}

我正在使用postman進行CURL請求,但是當我在 bash 中使用curl時也會出現此錯誤。

下面的代碼是我注冊新 API 調用的方式。

$application = AppFactory::create();

$application->group('/ambient', function(RouteCollectorProxy $routeCollector) {
    $routeCollector
        ->post('/register', RegisterAmbientController::class)
        ->setName('register-ambient');
});

你也可以在我的github中查看完整代碼: https : //github.com/JasterTDC/ardu-component/tree/feature/register-temp-humity

提前致謝 !

Slim 4 不會自動解析正文,除非它是基於表單的 POST 請求。 如果您的負載是 POST 或 PUT 中的 JSON 或 XML,那么您將需要一些正文解析中間件。

昨天添加了 Slim 4 的BodyParsingMiddleware

最簡單的使用方法是添加$app->addBodyParsingMiddleware(); 創建$app實例后。 像這樣的工作:

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Factory\AppFactory;
use Slim\Middleware\BodyParsingMiddleware;
use Slim\Psr7\Response;

$app = AppFactory::create();
$app->addBodyParsingMiddleware();

$app->post('/data', function (ServerRequestInterface $request): ResponseInterface {
    $data = $request->getParsedBody();

    $response = new Response();
    $response->getBody()->write(
        print_r($data, true)
    );
    return $response;
});

$app->run();

但是請注意,您需要在 composer.json 中使用dev-4.x或等待 4.1 之后的下一個次要版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM