简体   繁体   中英

Slim Framework v3, getting JSON data via POST issue

I'm am using the Slim Framework v3 and have some problems with accessing the JSON data I'm sending from a browser client to my REST API.

Currently I'm using $request->getParsedBody(); to access the data, but all it returns is a string and I don't want to parse it, because I think there's a better solution for this problem.

Here's what is sent by the client:

$data = array ();
$data ["key1"] = "value1";
$data ["key2"] = "value2";
$data ["key3"] = "value3";
$data = json_encode ( $data );

This produces {"key1":"value1","key2":"value2","key3":"value3"}

What happens on the server?

$app->post ( '/somePath', function ($request, $response) {
    $body = $request->getParsedBody();
    var_dump($body);
    return $response;
});

The var_dump(); is producing the following output:

string(86) "array(1) {
  ["{"key1":"value1","key2":"value2","key3":"value3"}"]=>
  string(0) ""
}
"

As you can see, $request->getParsedBody(); is returning a string. Is there any better way to do this?

I already tried to use $request->getBody(); , but that returns an object of the type Slim\\Http\\RequestBody and has only protected variables. I haven't found any function to access these protected variables.

Please remember that I'm using Slim v3, they have changed a lot of things from v2.

If there is no better way, do you have suggestions how to parse it the best way?

As reported by the Slim 3 docs:

JSON requests are converted into associative arrays with json_decode($input, true).

So getParsedBody is definitely the way to go. Instead, have you check the request type set by your client? It should be application/json in order to make the Slim request object do the correct interpretation of the raw body.

eg:

Content-Type: application/json

Seems that the problem is in the data that you're getting from the client. You're receiving a sort of var_dump or var_export output as the user in this case. According with the data that you receive, I would search something like this in your client code:

<?php var_export([json_encode($data) => '',],true);

On the server side the body can't be parsed because it's not a correct JSON string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM