[英]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.