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

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab