Hi,
I don’t understand, how I have to deal with JSON in a Request Object?
Adding a middleware as described in http://www.slimframework.com/docs/v4/objects/request.html#the-request-body does not work for me:
class JsonBodyParser 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);
// this request object contains an array in getParsedBody()
print_r(['$request' => $request]);
}
}
return $handler->handle($request);
}
}
$app = AppFactory::create();
$app->addBodyParsingMiddleware();
$app->add(new JsonBodyParser());
$app->post('/test/json', function(Request $request, Response $response) {
$response->getBody()->write(print_r([
'$_POST' => $_POST,
'getHeader(\'content-type\')' => $request->getHeader('content-type'),
'getMethod()' => $request->getMethod(),
'getParsedBody()' => $request->getParsedBody(), // empty
'getBody()' => $request->getBody()
], true));
});
curl --header "Content-Type: application/json" --request POST --data '{"name":"xyz"}' http://127.0.0.1/test/json