我遇到将Chrome预设休息客户端的mime类型content-type application/json
数据发布到精简框架网络服务的问题。
我尝试使用这些代码发送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;
...});
也尝试了这个
$params = json_decode($app->request()->getBody());
var_dumb($params); //get NULL value here
错误
Trying to get property of non-object to this `$name = $params->name;`
请帮我看看如何捕获application / json格式的数据? 谢谢
答案 0 :(得分:0)
根据上面的细节,假设您的原始JSON看起来像这样
{"name":"John Smith", "mail":"jhon@mail.com", "password":"foobar"}
您可以像这样
访问你的参数数组$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");
或者如果您通过Content-Type: application/x-www-form-urlencoded
在Advanced Rest客户端发帖,则可以使用$app->request->post();
访问您的阵列
$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");