【问题标题】:JSON error in node js undefined as prefix to post data节点 js 中的 JSON 错误未定义为发布数据的前缀
【发布时间】:2012-02-10 17:07:04
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript python json node.js


    【解决方案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.
    

    【讨论】:

    • 天哪。我犯的愚蠢错误...花了半天时间挖掘客户端和服务器代码..发现了这个.. ::]
    猜你喜欢
    • 1970-01-01
    • 2018-07-14
    • 2019-03-30
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多