尝试从Node.js将文档插入CouchDB时出现"bad_request invalid_json"错误 [英] Getting ' bad_request invalid_json' error when trying to insert document into CouchDB from Node.js

查看:104
本文介绍了尝试从Node.js将文档插入CouchDB时出现"bad_request invalid_json"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"}    

我的代码:

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.

I need to update data, so I replaced POST to PUT.

推荐答案

因为您将'data\n'编写为请求的正文,而这实际上不是有效的JSON.

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

可能是您的意思:

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

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

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

这篇关于尝试从Node.js将文档插入CouchDB时出现"bad_request invalid_json"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆