我有以下函数在 php 和 nodejs 之间进行通信:
function toNode($data){
//$data is array
//$data example
//$data = array("one"=>"yes","two"=>"no","three"=>array("yet"=>"another"))
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:'.$socket_port.'/posts');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_exec($ch);
$feedback = curl_getinfo($ch);
}
以下是 Nodejs console.log 接收数据的方式:
{ one: 'yes',
two: 'no',
'three[0][yet][0]':'another'} //<---
这是我希望数据如何显示在nodejs端:
{ one: 'yes',
two: 'no',
three: [ { yet: 'another' } ] } //<---
我到底怎样才能用curl实现这一点?我尝试过在接收信息的nodejs端使用此功能
function urldecode(str) {
return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
但是失败了,如果我没记错的话,什么也没有输出。另外,进一步用于处理数据的函数在来自 php curl 或 native Nodejs 中的函数(未进行 url 编码)之间共享因此,最好是在 php 端解决问题...有人可以帮我吗?非常感谢...
编辑:包括解析nodejs端的信息:
app.post('/posts', function(req, res){
if(req.headers.host == '127.0.0.1:'+socket_port) {
if(req.method == 'POST') {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, [[ "Content-Type", "text/plain"]
, ["Content-Length", 0]
]);
res.write('');
res.end();
furtherFunction(fields);
});
}
}
});
最佳答案
据我了解,您想要发送 json 数据。我这里没有看到任何json数据。我用谷歌搜索了一下。这里send-json-post-using-php ,我找到了如何在 php 中发送 json 数据。希望它会有所帮助。
关于php - 通过curl以指定格式发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34021817/