Slim 3 getParsedBody() always null and empty
Solution 1
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;
Solution 2
When I switch to slimframework version 4, I had to add :
$app->addBodyParsingMiddleware();
Otherwise the body was always null (even getBody())
Solution 3
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);
});
Solution 4
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!
Related videos on Youtube
animatorist
Updated on June 11, 2022Comments
-
animatorist almost 2 years
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 ?
-
Rendy Eko Prastiyo over 7 yearsCan you explain how your request send data to the app?
-
-
meun5 over 7 yearsThat will not work for Slim Framework 3, which is what the OP is using.
-
jcarrera over 7 yearsAre you sure? It works for me. Look at this stackoverflow.com/questions/28073480/…
-
meun5 over 7 yearsThat is for Slim Framework version 2, not for Slim Framework version 3. The way the requests work was heavily changed from 2 to 3.
-
ultrasamad almost 7 yearsI got NULL with var_dump($request->getParsedBody()); when using either PATCH or PUT request. But POST request returns the request body. Is there a different method for PATCH and PUT?
-
Rob Allen almost 7 years@ultrasamad Please create a separate question with a minimal PHP code example and the curl command used to show the problem.
-
zombat over 4 yearsThe question is about Slim version 3, not 4.
-
Peter Lenjo almost 4 yearsThank you, my Slim 4 search brought me here.
-
Samantha Adrichem almost 3 yearsEven though this question is about slim 3, you indeed find it always at the top and this answer is the perfect answer for slim 4 so thank you very much!