【发布时间】:2018-12-21 21:11:52
【问题描述】:
我有 Nodejs 服务器的其他 API,我正在尝试使用 PHP 对其进行 POST 调用。
我的php代码是:
function post_url($apiRoute,$data) {
$request_url = 'http://test-app.herokuapp.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
echo $data ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
我试过用不同形式的数据调用这个函数:
$g = array("_id" => "111");
$postapiresponse = post_url('/CCTRequest/get',json_encode($g));
或
$postapiresponse = post_url('/CCTRequest/get',json_encode(array("_id" => "111"));
但是在 Node.js 的服务器端,当我控制台日志 req.body 时,我得到这样的数据:
{ '{"_id":"111"}': '' }
我应该如何在 PHP 中传递数据,以便在 node.js 中获取正确的 obj,即:
{ '_id': '111' }
【问题讨论】:
-
不要手动对数据进行 json_encode,CURLOPT_POSTFIELDS 需要一个数组。
-
@castis 我试过发送数组。当我在服务器上发送这个数组(“_id”=>“111”)时,我在 req.body 中得到 {}
-
@castis curl_setopt($ch, CURLOPT_POSTFIELDS, array("_id" => "111"));试过这个。在服务器中获取 {}
-
请在 cmets 中分享 cURL