Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...