1

I'm trying to insert a document into CouchDB. While executing this code CouchDB returns the following error:

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

My code:

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 data, so I replaced POST to PUT.

DSblizzard
  • 4,007
  • 7
  • 48
  • 76

1 Answers1

6

Because you are writing 'data\n' as the body of your request, and that's not valid JSON indeed.

Probably, you meant:

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

instead of passing this as the body parameter of the options.

Ruben Verborgh
  • 3,545
  • 2
  • 31
  • 43
  • No, the error occures in preceding code, it remains even if I comment out this line. – DSblizzard Jul 25 '12 at 22:40
  • 1
    Yes, it also occurs if you comment out the line. Because you're not sending a body then, and that's also invalid JSON. Therefore, I suggested you *replace* the line `req.write('data\n');` with the code above. Can you try that instead of just commenting out? – Ruben Verborgh Jul 26 '12 at 07:15
  • Thank you very much, this simple operation drank from me a liter of blood. But can we reorganize code in such a way that "body" and other options lie together? – DSblizzard Jul 26 '12 at 11:13
  • 2
    What I'd recommend in that case, is to add a function that abstracts this behavior. Something like `function store(path, contents)`, to which you pass your path and body. The function then does the request, JSON encoding, etc. – Ruben Verborgh Jul 26 '12 at 12:30
  • In my case I had `\'` in my `startkey` and `endkey` values, and `request` did not translate those over to `'`.. – knownasilya Jul 13 '14 at 02:03