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

Arangodb import via http api using node.js

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

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

代码如下(与上面列出的大多数模块类似,只有细微的变化)。各种场景(单个文档导入等)似乎都指向 post 由于某种原因没有被正确识别的正文。

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 中使用它。我究竟做错了什么?这真让我抓狂。任何帮助,将不胜感激。非常感谢。

您可以使用 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(您尝试通过设置内容类型来实现)。 将针制作成实际 post 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 }