Unable to get JSON POST data submitted via Slim

I use Postman (in Chrome) to test subtle calls, but can't figure out how to get any published JSON data.

Im sending raw JSON:

{"name":"John Smith", "age":"30", "gender":"male"} 

With Content-Type: application / json in title

through POST:

 http://domain/api/v1/users/post/test/ 

Every attempt to get 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!

+6
source share
5 answers

Make sure that curry $app on the last nested route, for example:

 // Pass through $app $app->post('/test/', function () use ($app) { 

You do it everywhere, so I guess you just missed it.

+8
source

you need to get the body from the request:

$ app-> request-> getBody ();

http://docs.slimframework.com/request/body/

+1
source

In Slim 3, I used the body value in curl POST data, and it did not work. To fix this, I used this, the body is not an object 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 the body in docs

+1
source
  //You did not pass the ($app) in your post route... so make it correct $app->post('/test/', function () use ($app){ //now if you want to get json data so please try following code instead of print_r($app->request->headers); $us=$app->request->getbody(); //$us will get the json data now if you want to decode it and and want to get an array so try following.. $ar=json_decode($us,true); //now you have $ar array of json data use it where you want.. }); 
0
source

Try the following:

 $app->post('/test/', function () use ($app){ instead of print_r($app->request->headers); $ar=$app->request->getbody(); to get an array so try following.. $arry=json_decode($ar,true); }); 
0
source

Source: https://habr.com/ru/post/959140/


All Articles