如何将'content-type application / json'的数据发布到slim php rest服务

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

dongyanpai2701
dongyanpai2701 介意分享您提交的JSON对象?
5 年多之前 回复
dtng25909
dtng25909 您显示的错误与第一个代码段的第一部分有关。尝试评论它并尝试仅在第二个上工作。
5 年多之前 回复

1个回答

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");
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐