尝试从Node.js将文档插入CouchDB时出现'bad_request invalid_json'错误

时间:2012-07-25 10:24:46

标签: json node.js couchdb

我正在尝试将文档插入CouchDB。执行此代码时,CouchDB会返回以下错误:

STATUS: 400    
BODY: {"error":"bad_request","reason":"invalid_json"}    

我的代码:

var http = require('http')


var options = {
"host": "localhost",
"port": "5984",
"path": "/chinese",
"headers": {"content-type": "application/json"},
"method": "PUT",
"body": JSON.stringify({
    "_id":"rabbit",
    "_rev":"2-c31d8f403d44d1082b3b178ebef8d329",
    "Subject":"I like Plankton"
})
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.write('data\n');
req.end();

怎么了?

编辑:我需要更新数据,所以我将POST替换为PUT。

1 个答案:

答案 0 :(得分:5)

因为您正在撰写'data\n'作为请求的正文,而且这确实是无效的JSON。

可能,你的意思是:

req.write(JSON.stringify({"data": "somedata"}));

而不是将其作为选项的body参数传递。