[英]Invalid JSON Error at POST/PUT json with special characters using nodejs http.request()
我正在使用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
的字符串Content-Length
,但不包括以字节为单位的长度-特殊字符的长度可能更长。 尝试将行更改为此:
var stringifiedData = new Buffer(JSON.stringify(data));
这应该允许内容长度正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.