gpt4 book ai didi

javascript - Node js中的JSON错误未定义为发布数据的前缀

转载 作者:行者123 更新时间:2023-11-30 13:23:57 25 4
gpt4 key购买 nike

我无法将 json 发布到小型 node.js http 服务器。发布数据的前面似乎总是有一个“未定义”。我可能做的真的很蠢,所以我很抱歉!

我启动服务器并使用以下 py 脚本发布一些 json:

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

服务器得到这个

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

Node 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()

最佳答案

你必须定义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.

关于javascript - Node js中的JSON错误未定义为发布数据的前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9231751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com