animatorist
animatorist

Reputation: 113

Slim 3 getParsedBody() always null and empty

I'm am using the Slim Framework Version 3 and have some problems.

$app-> post('/', function($request, $response){
  $parsedBody = $request->getParsedBody()['email'];
  var_dump($parsedBody);
});

result is always:

null

Can you help me ?

Upvotes: 9

Views: 20339

Answers (4)

Thomas
Thomas

Reputation: 1354

When I switch to slimframework version 4, I had to add :

$app->addBodyParsingMiddleware();

Otherwise the body was always null (even getBody())

Upvotes: 31

Falk Müller
Falk Müller

Reputation: 11

In Slim 3, you must register a Media-Type-Parser middleware for this.

http://www.slimframework.com/docs/v3/objects/request.html

$app->add(function ($request, $response, $next) {
    // add media parser
    $request->registerMediaTypeParser(
        "text/javascript",
        function ($input) {
            return json_decode($input, true);
        }
    );

    return $next($request, $response);
});

Upvotes: 1

Rob Allen
Rob Allen

Reputation: 12778

It depends how you are sending data to the route. This is a POST route, so it will expect the body data to standard form format (application/x-www-form-urlencoded) by default.

If you are sending JSON to this route, then you need to set the Content-type header to application/json. i.e. the curl would look like:

curl -X POST -H "Content-Type: application/json" \
  -d '{"email": "[email protected]"}' http://localhost/

Also, you should validate that the array key you are looking for is there:

$parsedBody = $request->getParsedBody()
$email = $parsedBody['email'] ?? false;

Upvotes: 5

jcarrera
jcarrera

Reputation: 1068

Please, try this way:

$app-> post('/yourFunctionName', function() use ($app) {
  $parameters = json_decode($app->request()->getBody(), TRUE);
  $email = $parameters['email'];
  var_dump($email);
});

I hope this helps you!

Upvotes: 2

Related Questions