【问题标题】:POST application/json data not reaching serverPOST 应用程序/json 数据未到达服务器
【发布时间】:2022-01-24 19:21:05
【问题描述】:

我有一个在 docker 中运行的 Nginx 和 PHP 容器。当我运行以下请求时, $_POST 为空。 我使用 Phpstorm 选项“Break at the first line in PHP scripts”进行调试。

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

什么会导致 $_POST 为空?是否需要在 Nginx 中进行配置?

当我使用表单数据尝试请求时,它可以工作,但我需要它与 JSON 一起工作。

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

【问题讨论】:

    标签: php json docker nginx


    【解决方案1】:

    发布application/json数据时,$_POST始终为空,可以用PHP获取JSON请求体:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      相关资源
      最近更新 更多