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()
啊,謝謝,沒有意識到這 – nflacco 2012-02-10 17:31:43
神。我犯的愚蠢的錯誤...花了半天的時間挖掘客戶端和服務器代碼..並發現這個.. ::] – 2017-10-29 08:37:33