REST API GET/POST using jquery AJAX to get node us

2019-05-14 08:02发布

问题:

I'm new to REST API**(is that really my REST problem?)**

I want to get all node from neo4js by using Cypher

START n = node(*)
return n;

how do i use if i use jquery ajax POST or GET method

in doc it recommend

POST http://localhost:7474/db/data/cypher
Accept: application/json
Content-Type: application/json

In my code i write

 $.ajax({
      type:"POST",
      url: "http://localhost:7474/db/data/cypher",
      accepts: "application/json",
      dataType:"json",
      contentType:"application/json",
      data:{
             "query" : "start n  = node(*) return n",
             "params" : {}
           },
      success: function(data, textStatus, jqXHR){
                      alert(textStatus);
                        },
      error:function(jqXHR, textStatus, errorThrown){
                       alert(textStatus);
                        }
             });//end of placelist ajax  

What's my problem? The error alert is below

回答1:

You dont say what kind of error you get, but running exactly the same code as you, I get the following error:

XMLHttpRequest cannot load http://127.0.0.1:7474/db/data/cypher.
Origin http://127.0.0.1:3000 is not allowed by Access-Control-Allow-Origin.

So I am assuming that this is the error you are experiencing.

When performing a cross-domain Ajax call, there are two options:

  1. JSONP, which Neo4J does not support.

  2. Cross-Origin Resource Sharing (CORS). "The basic idea behind CORS is to use custom HTTP headers to allow both the browser and the server to know enough about each other to determine if the request or response should succeed or fail".

The OPTIONS request sent before the POST (preflight request), returns the following headers from the Neo4J REST server:

Access-Control-Allow-Origin:*
Allow:OPTIONS,POST
Server:Jetty(6.1.25)

A cruical header is missing here, namely the Content-Type header. This means that the POST request will fail when this header is sent with the POST request, which is exactly what is happening in your $.ajax() call.

The POST will succeed if you remove the following line

contentType:"application/json",

from your $.ajax() call.

This will prevent jQuery from sending the Content-Type header.