Home > Mobile >  POST application/json data not reaching server
POST application/json data not reaching server

Time:12-24

I have an Nginx and PHP container running in docker. When I run the following request, $_POST is empty. I use the Phpstorm option "Break at the first line in PHP scripts" to Debug.

curl -X POST 'localhost/api/v1/customers' -H 'Content-Type: application/json' --data-raw '{"id":"12345"}'

What can cause that the $_POST is empty? Is there a config in Nginx required?

When I try the request with form data, it works but I need that it works with JSON.

curl -X POST 'localhost/api/v1/customers' -H 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'id=12345'

CodePudding user response:

When posting application/json data, $_POST is always empty and you can obtain the JSON request body with PHP:

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
$ curl -X POST 'localhost/api/v1/customers' \
  -H 'Content-Type: application/json' \
  -d '{"id":"12345"}'

Array
(
    [id] => 12345
)
  • Related