N
N
nepster-web2013-12-22 03:48:02
PHP
nepster-web, 2013-12-22 03:48:02

How to pass multidimensional array to node.js?

Task to pass multidimensional array from php to node.js
php

$data = array();
                    
                    $data['rules'] = array(
                        array('count_player' => 2),
                        array('team_game'    => 0),
                        array('time_hit'     => 120),
                    );
                    $data['users'] = array(
                        array('user_id'=>1,'avatar'=>'url','login'=>'Nepster','root'=>1),
                        array('user_id'=>2,'avatar'=>'url','login'=>'Zowen','root'=>0),
                    );
                  
                    $data = json_encode($data);
                    
                    $curl = curl_init();
                    
                    curl_setopt($curl, CURLOPT_URL, "http://localhost:8888");
                    curl_setopt($curl, CURLOPT_POST, 1);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                
                    curl_exec($curl);

Node (As @Scorpi suggested )
var http = require('http'),
    formidable = require('formidable'),
    util = require('util');

http.createServer(function (req, res) {
    if (req.method == 'POST') {
        
        var form = new formidable.IncomingForm();
    
        form.parse(req, function(err, fields, files) 
        {
        
            console.log(fields);
            
    	});
    }
  	res.end();
}).listen(8888);

console.log('START');

If you pass array('test'=>'data');
Everything will be fine if you try a multidimensional array everywhere we get an array, if you try to transfer json, an error occurs when parsing unexpected token o

Please tell me how can I transfer the data?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Timur Zurbaev, 2013-12-24
@tzurbaev

$data = http_build_query($data);
instead of json_encode() won't help?

A
Andrey Degtyaruk, 2013-12-24
@hlogeon

Wrote in Node, never had problems with creating a multi-dimensional array, whether from php, whether from a form via http.
How did you do it? json_encode($data); -> transmit via GET or POST
On the receiving side, something like JSON.parse();
If you get an unexpected token o error , try printing the resulting value to the console and typing it into any online JSON parser. And it will immediately become clear to you what and where went wrong. In general, no problems should arise after output to the console)

W
Walt Disney, 2013-12-22
@ruFelix

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);should not be a string, you are not expecting form data from the node.js side.
Write something like:
Or parse raw data on the side of the node, but this is a more confused way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question