/ / Chyba JSON v uzle js nedefinovaná ako predpona na zaúčtovanie údajov - javascript, python, json, node.js

Chyba JSON v uzle js nedefinovaná ako predpona na odosielanie údajov - javascript, python, json, node.js

Mám problémy s uverejnením json na malom http serveri node.js. Zdá sa, že údaje o publikácii majú vždy pred sebou „nedefinovanú“. Pravdepodobne som naozaj hlúpy, takže sa ospravedlňujem!

Spustím server a pošlem nejaký json s skriptom skriptu nižšie:

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

Server to získa

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

uzol http server

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 skript robiť 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()

odpovede:

3 pre odpoveď č. 1

Musíte definovať počiatočnú hodnotu content:

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

Pri prvom hovore na data event, request.content ešte neexistuje. Reťazcové znázornenie nedefinovanej vlastnosti je "undefined".

Na ilustráciu mechanizmu za tým 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.