节点js中的JSON错误未定义为发布数据的前缀

时间:2012-02-10 17:07:05

标签: javascript python json node.js

我在将json发布到一个小node.js http服务器时遇到了麻烦。发布数据似乎总是在其前面有一个“未定义”。我可能真的很蠢,所以我道歉!

我启动服务器并使用下面的py脚本发布一些json:

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

服务器获取此

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

节点http服务器

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脚本做帖子

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 个答案:

答案 0 :(得分:3)

您必须定义content的初始值:

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

第一次调用data事件时,request.content尚不存在。未定义属性的字符串表示形式为"undefined"

因此,为了说明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.