我有以下功能可以在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' } ] } //<---
我怎样才能使卷曲发生呢?我已经尝试在接收到的信息中使用此功能
function urldecode(str) {
return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
但是它失败了,如果我没记错的话,什么也没输出。另外,用于处理数据的函数在php curl或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数据。我go了一下。在这里send-json-post-using-php,我发现了如何在php中发送json数据。希望它会有所帮助。