Im using Postman (in Chrome) to test Slim calls but cant figure out how to get any of the posted JSON data.
Im submitting raw JSON:
{"name":"John Smith", "age":"30", "gender":"male"}
With Content-Type: application/json in the header
via POST to:
http://domain/api/v1/users/post/test/
Every attempt to get the JSON data gives a fatal error (see code comments below)
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->add(new \Slim\Middleware\ContentTypes());
$app->group('/api/v1', function () use ($app) {
$app->group('/users/post', function () use ($app) {
$app->post('/test/', function () {
print_r($app->request->headers); //no errors, but no output?
echo "Hello!"; // outputs just fine
$data = $app->request()->params('name'); //Fatal error: Call to a member function request() on a non-object
$data = $app->request->getBody(); //Fatal error: Call to a member function getBody() on a non-object
$data = $app->request->post('name'); //Fatal error: Call to a member function post() on a non-object
$data = $app->request()->post(); //Fatal error: Call to a member function request() on a non-object
print_r($data);
echo $data;
});
});
});
$app->run();
?>
What am I missing?
Thanks!
Make sure to curry $app
into the last nested route, like so:
// Pass through $app
$app->post('/test/', function () use ($app) {
You're doing it everywhere else, so I'm assuming you just overlooked it.
you have to get the body from the request:
$app->request->getBody();
http://docs.slimframework.com/request/body/
In Slim 3 I've used the value of body in curl POST data and it didn't work, to fix this I've used this, the body is object not string:
$app->post('/proxy', function($request, $response) {
$data = $request->getBody()->getContents();
$response->getBody()->write(post('http://example.com', $data));
});
You can check more methods on body in docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With