简体   繁体   中英

Correct way to provide the 'query' parameter to Neo4j within Cypher REST API in node.js

How to compose correct Cypher query through POST request to Neo4j in node.js?

Code:

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();

Result:

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

Expected result:
List of all nodes (same as POST /db/data/cypher {"query":"START root=node(*) RETURN root"} in Neo4j console)


Solution (thanks to 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(); 

You supplied 'query' as an unrecognized option for http.request , but you need to write it as the body of the request. You also probably want to move the 'Content-Type' line inside the headers option object.

Take a look at the example from the node docs:

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

您可能还想考虑使用像Express这样的框架

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM