douqihua6212 2015-04-10 08:37
浏览 34

如何将'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

  • 写回答

1条回答

  • doumian3780 2015-04-15 18:34
    关注

    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");
    
    评论

报告相同问题?

悬赏问题

  • ¥20 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏