无法使用Slim v3获取JSON POST数据

时间:2016-05-28 14:22:10

标签: php json slim

我正在使用Slim v3。通过作曲家安装。 这是我的register.php文件:

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';


$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);


//-------------- Register ------------------ 
$app->post('/', function (Request $request, Response $response   ,$args)    use($app) {

$json =$request->getParams();
$data = json_decode($json, true);
$response->getBody()->write($data);

return $response;
});
$app->run();

当我发布样本Json时{"name":"jack", "age":"10", "gender":"male"} 通过postman我得到RuntimeException错误Could not write to stream。 我已经使用$app->request()->post();$request->getParams();以及$request->getParsedBody();但我还面临其他错误,例如未定义的方法等等。 请帮助我。

2 个答案:

答案 0 :(得分:2)

你可以使用

//-------------- Register ------------------ 
$app->post('/', function (Request $request, Response $response, $args) use ($app) {
    $json =$request->getParams();
    return $response->withJson($json);
});

答案 1 :(得分:1)

我认为你应该在请求中使用getBody(),而不是getParams

$json =$request->getBody();