问题
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 !
回答1:
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 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();
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.
来源:https://stackoverflow.com/questions/57402634/request-parameters-are-empty-using-slim-v4-1