我使用Postman(在Chrome中)测试Slim调用,但无法弄清楚如何获取任何已发布的JSON数据。
我提交原始JSON:
{"name":"John Smith", "age":"30", "gender":"male"}
在标题
中使用Content-Type:application / json通过POST到:
http://domain/api/v1/users/post/test/
每次尝试获取JSON数据都会产生致命错误(请参阅下面的代码注释)
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->add(new \Slim\Middleware\ContentTypes());
$app->group('/api/v1', function () use ($app) {
$app->group('/users/post', function () use ($app) {
$app->post('/test/', function () {
print_r($app->request->headers); //no errors, but no output?
echo "Hello!"; // outputs just fine
$data = $app->request()->params('name'); //Fatal error: Call to a member function request() on a non-object
$data = $app->request->getBody(); //Fatal error: Call to a member function getBody() on a non-object
$data = $app->request->post('name'); //Fatal error: Call to a member function post() on a non-object
$data = $app->request()->post(); //Fatal error: Call to a member function request() on a non-object
print_r($data);
echo $data;
});
});
});
$app->run();
?>
我错过了什么?
谢谢!
答案 0 :(得分:8)
确保将$app
加入到最后一个嵌套路线中,如下所示:
// Pass through $app
$app->post('/test/', function () use ($app) {
你在其他任何地方都这样做,所以我假设你只是忽略了它。
答案 1 :(得分:1)
答案 2 :(得分:1)
在Slim 3中,我在curl POST数据中使用了body的值,但它没有用, 为了解决这个问题我已经使用了这个,身体是对象而不是字符串:
$app->post('/proxy', function($request, $response) {
$data = $request->getBody()->getContents();
$response->getBody()->write(post('http://example.com', $data));
});
您可以在docs
中检查身体上的更多方法答案 3 :(得分:0)
//You did not pass the ($app) in your post route... so make it correct
$app->post('/test/', function () use ($app){
//now if you want to get json data so please try following code instead of print_r($app->request->headers);
$us=$app->request->getbody();
//$us will get the json data now if you want to decode it and and want to get an array so try following..
$ar=json_decode($us,true);
//now you have $ar array of json data use it where you want..
});
答案 4 :(得分:0)
试试这个:
$app->post('/test/', function () use ($app){
instead of print_r($app->request->headers);
$ar=$app->request->getbody();
to get an array so try following..
$arry=json_decode($ar,true);
});