使用邮递员通过原始json发送POST数据

时间:2016-08-18 00:09:20

标签: php json rest postman

我有Postman(在Chrome中没有打开的那个),我正在尝试使用原始json进行POST请求。

在Body选项卡中,我选择了“raw”和“JSON(application / json)”这个主体:

{
    "foo": "bar"
}

对于标题我有1 Content-Type: application/json

在PHP方面,我现在正在做print_r($_POST);,我得到一个空数组。

如果我使用jQuery并执行:

$.ajax({
    "type": "POST",
    "url": "/rest/index.php",
    "data": {
        "foo": "bar"
    }
}).done(function (d) {
    console.log(d);
});

我得到了预期的结果:

Array
(
    [foo] => bar
)

那为什么不与Postman合作?

邮差截图:

enter image description here

和标题:

enter image description here

5 个答案:

答案 0 :(得分:23)

jQuery不同,为了阅读原始JSON,您需要在PHP中对其进行解码。

print_r(json_decode(file_get_contents("php://input"), true));

php://input是一个只读流,允许您从请求正文中读取原始数据。

$_POST是表单变量,您需要切换到form中的postman单选按钮,然后使用:

foo=bar&foo2=bar2

使用json发布原始jquery

$.ajax({
    "url": "/rest/index.php",
    'data': JSON.stringify({foo:'bar'}),
    'type': 'POST',
    'contentType': 'application/json'
});

答案 1 :(得分:7)

meda的答案是完全合法的,但是当我复制代码时,我收到了错误!

"php://input"中某处有无效字符(可能是其中一个引号?)。

当我手动输入-n代码时,它有效。 我花了一段时间才弄明白!

答案 2 :(得分:6)

只需从二进制旁边的下拉列表中检查JSON选项;当您单击原始时。这应该做

skill synon pass json to postman

答案 3 :(得分:4)

我遇到了同样的问题,代码对我有用:

$params = (array) json_decode(file_get_contents('php://input'), TRUE);
print_r($params);

答案 4 :(得分:2)

安装Postman本机应用程序,Chrome扩展程序已被弃用。 (我的窗口在自己的窗口中打开,但仍作为Chrome应用运行)

相关问题