使用nodejs http.request()使用特殊字符的post/put json的json错误无效



我正在使用node.js http模块将JSON数据放入CouchDB。此JSON包含一个特殊的字符"ä",该字符引起couchdb响应" Invalid_json"错误。删除或替换此特殊字符后,数据将成功保存。我的node.js代码:

var data = {
    "a": "Gerät"
};
var stringifiedData = JSON.stringify(data);
var http = http || require("http");
var requestOptions = {
    "host": "localhost",
    "port": "5984",
    "method": "PUT",
    "headers": {
        "Content-Type": "application/json",
        "Content-Length": stringifiedData.length
    },
    "path": "/testdb/test"
};
var req = http.request(requestOptions, function (res) {
    res.setEncoding("utf8");
    res.on("data", function (chunk) {
      console.log("Response: " + chunk);
    });
});
console.log("stringifiedData: ", stringifiedData);
req.end(stringifiedData);

有趣的是,如果我将这些数据保存到JSON文件中并使用Curl命令将其放入CouchDB中,则保存数据没有任何问题。

curl -X PUT -d @test.json http://localhost:5984/testdb/test

我是否错过了使用nodejs http.request()的一些编码配置?我尝试将"gerät"转换为'utf8'编码: Buffer.from("Gerät", "latin1").toString("utf8);,但没有帮助。

将包含此特殊字符的JSON发布给COUCHDB /_bulk_docs API。

也存在相同的问题。

问题是您包括Content-Length的字符串长度,而不是字节中的长度 - 特殊字符可以具有更长的长度。尝试更改以下行:

var stringifiedData = new Buffer(JSON.stringify(data));

这应该允许内容长度正确。

论坛帖子讨论问题

最新更新