使用node.js通过http api导入Arangodb

时间:2015-06-22 18:47:18

标签: node.js arangodb

我正在尝试使用来自各种节点模块(如needle,http,request)的http api将json数组导入arangodb。每次我收到以下错误或类似错误:

{ error: true,
  errorMessage: 'expecting a JSON array in the request',
  code: 400,
  errorNum: 400 }

代码如下(类似于上面列出的大多数模块,但有很小的变化)。各种情况(单个文档导入等)似乎都指向由于某种原因未正确识别帖子正文。

var needle = require('needle');

var data = [{
    "lastname": "ln",
    "firstname": "fn",
},
{
    "lastname": "ln2",
    "firstname": "fn2"
}];

var options = {  'Content-Type': 'application/json; charset=utf-8'  };


needle.request('POST', 'http://ip:8529/_db/mydb/_api/import?type=array&collection=accounts&createCollection=false', data, options,     function(err, resp) {
    console.log(resp.body);
});

虽然我能够使用curl和浏览器开发工具上传文档,但我无法在node.js中使用它。我究竟做错了什么?这真让我抓狂。任何帮助,将不胜感激。非常感谢你。

1 个答案:

答案 0 :(得分:2)

您可以使用ngrep(或wireshark)快速找出错误的内容:

ngrep -Wbyline port 8529 -d lo
T 127.0.0.1:53440 -> 127.0.0.1:8529 [AP]
POST /_db/mydb/_api/import?type=array&collection=accounts& createCollection=true HTTP/1.1.
Accept: */*.
Connection: close.
User-Agent: Needle/0.9.2 (Node.js v1.8.1; linux x64).
Content-Type: application/x-www-form-urlencoded.
Content-Length: 51.
Host: 127.0.0.1:8529.
.
##
T 127.0.0.1:53440 -> 127.0.0.1:8529 [AP]
lastname=ln&firstname=fn&lastname=ln2&firstname=fn2

要发送到ArangoDB的主体必须是json(当您尝试通过设置内容类型来实现)。 制作针以实际发布json的方法是这样的:(见https://github.com/tomas/needle#request-options

var options = {
    Content-Type: 'application/json; charset=utf-8',
    json: true
};

产生适当的回复:

{ error: false,
  created: 2,
  errors: 0,
  empty: 0,
  updated: 0,
  ignored: 0 }