1

I am trying to post an associative array to another Node.js server, internaly to my server:

First server does a POST request like this with Request:

var request = require('request');
request.post('http://localhost:8084/',{ json: {"isposted": {"ok":"val"}}});

Second server's result is this:

{ '{"isposted":{"ok":"val"}}': '' }

Instead of:

{"isposted":{"ok":"val"}}

Server's (2nd) source code to parse the data is this:

var http = require('http');
var qs = require('qs');

var processRequest = function(req,callback) {
    var body='';
    req.on('data', function(data) { body+=data; });
    req.on('end',  function() { callback(qs.parse(body)); });
}

var server2 = http.createServer(function(req, res) {
    processRequest(req,function(data){
        try
        {
            data=JSON.parse(data.jsonData);
        }
        catch(e)
        {
            data=data;
        }
        console.log(data);
    });
 });

4
  • Someone edited my post, and removed the important information... Commented Feb 21, 2016 at 18:20
  • And now people down-voting it because the edit was making no sense Commented Feb 21, 2016 at 18:21
  • Sorry, I've missed a part in the first edit - the last edit you rolled back had all the information of your original post, but well formatted Commented Feb 21, 2016 at 18:24
  • Your request code has an extra } in it, and I've no idea where request is coming from. Presumably you are requiring some module, but which one and where is the code for it? It's hard to help you if you don't create a proper test case. (I haven't even looked at the server half of this yet) Commented Feb 21, 2016 at 18:40

1 Answer 1

1

qs is the wrong package to decode JSON like this: callback(qs.parse(body));. Try just using JSON.parse like this: callback(JSON.parse(body));

Try this to support different types of encoding:

req.on('end',  function(){ 
    if ('application/json' === req.headers['content-type']) {
        callback(JSON.parse(body)); 
    }
    else {
        callback(qs.parse(body));
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks it's working! But I also need qs.parse to decode data posted as GET, How can I decide if it should be parsed with JSON or QS?
You can use for instance body-parser and decide based on Content-Type-header, which is the recommended way to do it.
thanks, but I am not using express and I can't figure how to determine what is the Content-Type. I figured it's stated in res["_header"], but seems difficult to just extract the content-type from it
Nevermind, I found using req.headers['content-type']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.