2012-02-10 35 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