php 无法获取通过Slim提交的JSON POST数据

wmvff8tz  于 2023-03-07  发布在  PHP
关注(0)|答案(6)|浏览(166)

我正在使用Postman(在Chrome中)来测试Slim调用,但不知道如何获取任何发布的JSON数据。
我正在提交原始JSON:

{"name":"John Smith", "age":"30", "gender":"male"}

具有内容类型:标题中的应用程序/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();
?>

我错过了什么?
谢谢!

bq8i3lrv

bq8i3lrv1#

确保咖喱$app放入最后一个嵌套的路由中,如下所示:

// Pass through $app
$app->post('/test/', function () use ($app) {

你在其他地方都这样,所以我猜你只是忽略了它。

czq61nw1

czq61nw12#

你必须从请求中获取主体:
$app-〉请求-〉获取正文();
http://docs.slimframework.com/request/body/

gr8qqesn

gr8qqesn3#

在Slim 3中,我在curl POST数据中使用了body的值,但它不起作用,为了解决这个问题,我使用了这个方法,body是对象而不是字符串:

$app->post('/proxy', function($request, $response) {
    $data = $request->getBody()->getContents();
    $response->getBody()->write(post('http://example.com', $data));
});

可以在文档中检查body上的更多方法

yhuiod9q

yhuiod9q4#

//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..
    });
vlurs2pr

vlurs2pr5#

试试这个:

$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);

    });
xiozqbni

xiozqbni6#

默认情况下,Slim似乎不支持JSON的接收。你必须创建一个中间件类才能读取它。你可以在这里找到更多信息:https://www.slimframework.com/docs/v4/objects/request.html#the-request-body
但是,它始终能够读取以application/x-www-form-urlencoded形式发送的请求

相关问题