在node.js中的Cypher REST API中为Neo4j提供'query'参数的正确方法

时间:2013-07-25 21:05:17

标签: node.js rest neo4j cypher node-neo4j

如何通过对node.js中的Neo4j的POST请求撰写正确的Cypher查询?

代码:

var http = require('http');

var options = {
  host: 'a90cfa68c.hosted.neo4j.org',
  port: 7357,
  path: '/db/data/cypher',
  method: 'POST',
  headers: {               
    'Authorization': 'Basic ' + new Buffer("<login>:<password>").toString('base64')                  
  },
  "Content-Type" : "application/json",
  "query" : "START root=node(*) RETURN root" // <--- Doesn't work :(
};

http.request(options, function(res) {
      console.log('STATUS: ' + res.statusCode);
      console.log('HEADERS: ' + JSON.stringify(res.headers));
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
      });
}).end();

结果:

STATUS: 400
HEADERS: {"content-length":"340","content-encoding":"UTF-8","content-type":"application/json","access-control-allow-origin":"*","server":"Jetty(6.1.25)"}
BODY: {
  "message" : "You have to provide the 'query' parameter.",
  "exception" : "BadInputException",
  "stacktrace" : [ "org.neo4j.server.rest.web.CypherService.cypher(CypherService.java:63)", "java.lang.reflect.Method.invoke(Method.java:597)", "org.neo4j.server.extension.auth.AuthenticationFilter.doFilter(AuthenticationFilter.java:57)" ]
}

预期结果:
所有节点的列表(与Neo4j控制台中的POST /db/data/cypher {"query":"START root=node(*) RETURN root"}相同)

<小时/> 解决方案(感谢Andrew Palumbo):

// Changes goes here:
var req = http.request(options, function(res) {
      console.log('STATUS: ' + res.statusCode);
      console.log('HEADERS: ' + JSON.stringify(res.headers));
      res.setEncoding('utf8');
      res.on('data', function (chunk) {   
      console.log('BODY: ' + chunk);
      });
});
// Writing into body:
req.write('{"query":"START root=node(*) RETURN root"}');
req.end();

2 个答案:

答案 0 :(得分:3)

您提供了'query'作为http.request的无法识别的选项,但您需要write作为请求的正文。您可能还想在headers选项对象中移动“Content-Type”行。

查看节点docs中的示例:

http://nodejs.org/api/http.html#http_http_request_options_callback

答案 1 :(得分:1)

您可能还想考虑使用Express

这样的框架