【发布时间】:2019-06-17 21:32:25
【问题描述】:
我正在将 Node.js 中的 POST 请求发送到 php 服务器。在请求中,我将 json 作为对象而不是字符串。
Node.js 请求:
var request = require('request');
let data = { "name":"John", "age":30, "car":null };
request.post({
headers: {'content-type' : 'application/json; charset=utf-8'},
url: 'http://0.0.0.0:9000/html.php',
method: 'POST',
json: data
}, function(error, response, body){
console.log(body);
});
html.php:
<?php
# Get JSON as an object
$json = file_get_contents('php://input');
$name = $json->name;
echo $json // Prints out the whole json correctly
echo $name; // Prints out "undefined"
我希望输出是“John”而不是“undefined”
【问题讨论】:
-
undefined 是一个 js 错误 - PHP 输出的 js 中有一个错误 - 而不是 PHP 中的错误
-
$json是一个字符串。使用前需要解码:json_decode($json); -
@sergiu.siminiuc 我向你保证——不可能
-
请向我们展示
echo $json的输出 -
无法将 JSON 作为对象发送。你已经证明你用
echo $json;发送了一个字符串