2

I've the following function to communicate between php and 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);

}

Here is how the nodejs console.logs the data received:

 { one: 'yes',
 two: 'no',
'three[0][yet][0]':'another'}         //<---

And here is how I want the data to appear in nodejs side:

{ one: 'yes',
two: 'no',
three: [ { yet: 'another' } ] }       //<---

How exactly can I make this happen with curl? I've tried using this function on received information nodejs side

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}

but it fails, outputing nothing If I remember correctly. Also, the function used further to treat the data is shared between what comes from php curl or natively in nodejs (which is not url encoded) so, the best would be to solve the problem right in php side... Could someone help me here? Thank you very much...

EDIT: including parsing of information nodejs side:

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);                
            });
        }
    }

});
Fane
  • 1,978
  • 8
  • 30
  • 58

1 Answers1

0

What i understand, you want so send json data. I haven't seen any json data here. I googgled it. Here send-json-post-using-php, i found how to send json data in php. Hope it will help.

Community
  • 1
  • 1
xdeepakv
  • 7,835
  • 2
  • 22
  • 32