简体   繁体   中英

How to post data of 'content-type application/json' to slim php rest service

i am having issue for posting data of mime type content-type application/json from Chrome Advance rest Client to slim framework web service. I tried these codes to send in application/json

$app->post('/register', function() use ($app) {
            $app->add(new \Slim\Middleware\ContentTypes());            
            $params = $app->request->getBody();
            $name = $params->name;
            $email = $params->email;
            $password = $params->password;
            ...});

tried this also

$params = json_decode($app->request()->getBody());


 var_dumb($params); //get NULL value here

Getting errors of

Trying to get property of non-object to this `$name = $params->name;`

Please help me how to catch application/json format of data? Thank you

As per the above details, assuming your raw JSON looks something like this

{"name":"John Smith", "mail":"jhon@mail.com", "password":"foobar"}

You can access your params array like this

$app->post('/register', function () use ($app) {
$params =  $app->request->getBody() ;
$params = array_filter($params);

if(!empty($params)){
    $name = $params['name'];
    $mail = $params['mail'];
    $pass = $params['password'];

   // print $name;
  }

})->name("register");

or if you are posting in Advanced Rest client via Content-Type: application/x-www-form-urlencoded you can use $app->request->post(); to access your array

$app->post('/register/', function () use ($app) {

   $userInfo = $app->request()->params() ;
   //or
   $userInfo =  $app->request->post() ;
   $name = $userInfo['name'];
   $mail = $userInfo['email'];
   $pass = $userInfo['password'];

 // print $name

})->name("register");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM