Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

php - Request parameters are empty using Slim v4.1

I'm using Slim v4 for a little arduino components API. When I do a POST call over my controller, I get an empty request body without the parameters I sent to it.

In code below, in $parameters variable I have a NULL.

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

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

I'm using postman for doing CURL requests, but also this error shows up when I use curl in bash.

The code below is the way I register a new API call.

$application = AppFactory::create();

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

You can also see the full code in my github: https://github.com/JasterTDC/ardu-component/tree/feature/register-temp-humidity

Thanks in advance !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Slim 4 doesn't automatically parse the body unless it's a form-based POST request. If your payloads are JSON or XML in a POST or PUT, then you'll need some body parsing middleware.

BodyParsingMiddleware for Slim 4 was added yesterday.

The easiest way to use it is to add $app->addBodyParsingMiddleware(); after you have created your $app instance. Something like this works:

use PsrHttpMessageResponseInterface;
use PsrHttpMessageServerRequestInterface;
use SlimFactoryAppFactory;
use SlimMiddlewareBodyParsingMiddleware;
use SlimPsr7Response;

$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();

Note however, that you'll need to be on dev-4.x in your composer.json or wait for the next minor release after 4.1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...