1

I'm having trouble posting json to a little node.js http server. Post data always seems to have an 'undefined' on the front of it. I'm probably doing really stupid, so my apologies!

I start the server and post some json with the below py script:

>>node simplehttp.js
>>python post.py '{"foo":"bar"}'

The server gets this

>>Request received: undefined{"foo": "bar"}
Invalid JSON:undefined{"foo": "bar"}

node http server

var http = require("http"); // http-server

var server_http = http.createServer(
    // Function to handle http:post requests, need two parts to it
    // http://jnjnjn.com/113/node-js-for-noobs-grabbing-post-content/
    function onRequest(request, response) {
        request.setEncoding("utf8");

        request.addListener("data", function(chunk) {
            request.content += chunk;
        });

        request.addListener("end", function() {
            console.log("Request received: "+request.content);

            response.writeHead(200, {"Content-Type": "text/plain"});
            response.write("Thanks for sending a message");
            response.end();

            try {
                json = JSON.parse(request.content);
                if(json.m !== undefined){
                    console.log("m: "+json.m);
                }

            } catch (Error) {
                console.log('Invalid JSON:' + request.content);
            }
        });
    }
);

server_http.listen(9002);

python script to do post

import sys
import json
import httplib, urllib, urllib2

# Get parameters
if len(sys.argv) < 2:
    sys.stderr.write('Usage: python post.py [JSON Message]\n')
    sys.exit(1)

values = json.loads(sys.argv[1])
headers = {"Content-type": "application/json"}

conn = httplib.HTTPConnection('127.0.0.1', 9002)
headers = {"Content-type": "application/json"}
conn.request("POST", "", json.dumps(values), headers)
response = conn.getresponse()

print "response.status: "+response.status
print "response.reason: "+response.reason
print "response.read: "+response.read()
conn.close()

1 Answer 1

3

You have to define the initial value of content:

function onRequest(request, response) {
    request.content = "";

At the first call to the data event, request.content does not exist yet. The string representation of an undefined property is "undefined".

So, to illustrate the mechanism behind request.content += chunk;:

request.content += chunk;                    // is equivalent to
request.content = request.content + chunk;   // but request.content is undefined
request.content = undefined       + chunk;   // String concatenation, so
request.content = "undefined"     + chunk;   // <-- This
// Example, chunk = '{}'  --> request.content = "undefined{}"

// After this step, `request.content` is defined, and future calls to
//  request.content += chunk;   are plain string concatenations.
Sign up to request clarification or add additional context in comments.

1 Comment

god. the stupid mistake I make... spent half a day digging client and server code.. and found this .. ::]

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.