Имам проблеми с публикуването на json на малък http-сървър на node.js. Данните за публикациите винаги изглеждат „неопределени“ отпред. Вероятно правя наистина глупаво, така че извиненията ми!
Стартирам сървъра и публикувам някои 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 скрипт, за да публикувате
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 за отговор № 1Трябва да определите началната стойност на 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.