2012-02-10 41 views
1

我无法将json发布到一个小的node.js http服务器。发布数据的前面似乎总是有一个'未定义'的数据。我可能做的很蠢,所以我的道歉!节点js中的JSON错误未定义为发布数据的前缀

我启动服务器,并上传了一些JSON与下面的py脚本:

>>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脚本做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() 

回答

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. 
+0

啊,谢谢,没有意识到这 – nflacco 2012-02-10 17:31:43

+0

神。我犯的愚蠢的错误...花了半天的时间挖掘客户端和服务器代码..并发现这个.. ::] – 2017-10-29 08:37:33