通过cURL将JSON从PHP发送到node.js
我想将PHP脚本中的JSON数据发送到node.js服务器 我的PHP文件看起来:通过cURL将JSON从PHP发送到node.js,php,node.js,curl,Php,Node.js,Curl,我想将PHP脚本中的JSON数据发送到node.js服务器 我的PHP文件看起来: $data = array("name" => "Lorerm", "age" => "18"); $data_string = json_encode($data);
$data = array("name" => "Lorerm", "age" => "18");
$data_string = json_encode($data);
$ch = curl_init('http://localhost:3000/push');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
curl_exec($ch);
在node.js中我应该做什么
app.all('/push', function(req, res) {
// what to do here?
});
您的数据将在req.body中提供
希望有帮助:)通过执行
console.log(res)
和console.log(req)
@C0dekid.php检查是否发布了数据。req/res上没有我的数据。你在node.js服务器中添加了body解析器吗?我有“var bodyParser=require('body-parser')”。put app.use(bodyParser.json());use(bodyParser.urlencoded({extended:false}));在那之后啊,现在它开始工作了。你真棒,谢谢你的工作。
app.all('/push', function(req, res) {
console.log(req.body.name); // Lorem
console.log(req.body.name); // 18
res.status(200).json({data:req.body); // will give { name: 'Lorem',age:18'} in response
});