nflacco
nflacco

Reputation: 5082

JSON error in node js undefined as prefix to post data

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()

Upvotes: 1

Views: 2310

Answers (1)

Rob W
Rob W

Reputation: 349042

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.

Upvotes: 3

Related Questions