javascript - Parsing an array posted to nodejs server using querystring -


i use querystring parse data posted client. first time posting array, , i'm having same issue.

client side:

        $.ajax({         url: 'myurl',         type: "post",         data: {ids: ["str1","str2","str3"]},         success: function (msg) {             location.reload();         },         error: function (msg) {             alert("servererror");         },         cache: false,         }); 

server side:

var body='';    req.on('data', function(chunk) {     body += chunk.tostring();    });    req.on('end', function() {     var parsedbody = querystring.parse(body);     console.log(parsedbody);// {'ids[]':["str1","str2","str3"]} 

my problem? well, first note comment: key ids[] intead of ids. strange , annoyng. , big problem: if pass array 1 string this:

 data of ajax request--> data: { ids: ["str1"] } 

the console.log becomes

console.log(parsedbody);// {'ids[]':"str1"} console.log(parsedbody['ids[]'].length);// 4 (instead of 1) 

as can see array become string , problem.

you create own wrapper around querystring.parse(). example:

var qs = require('querystring');  function parseqs(str) {   var result = qs.parse(str),       keys = object.keys(result);    (var = 0, len = keys.length, key, newkey; < len; ++i) {     key = keys[i];     if (key.slice(-2) === '[]') {       newkey = key.slice(0, -2);       if (!array.isarray(result[key]))         result[newkey] = [ result[key] ];       else         result[newkey] = result[key];       delete result[key];     }   }    return result; }  console.dir(parseqs('foo[]=bar&baz=bla&quux[]=123&quux[]=456')); // outputs: // { baz: 'bla', //   foo: [ 'bar' ], //   quux: [ '123', '456' ] } 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -