Getting "bad_request invalid_json" error while trying to insert a document into CouchDB from Node.js

I am trying to insert a document in CouchDB. When executing this code, CouchDB returns the following error:

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

My code is:

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

What's wrong?

EDIT: I need to update the data, so I replaced POST with PUT.

+1
source share
1 answer

Because you are writing 'data\n'as the body of your request and really invalid JSON.

Did you mean:

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

instead of passing it as a parameter bodyparameter.

+5
source

All Articles