I am trying to call Neo4j API from jquery.
when i am invoking GET requests it works perfectly
GET request endpoint
http://localhost:7474/db/data/node/10
but when i am invoking POST requests with json body it returns following error.
POST request endpoint
http://localhost:7474/db/data/cypher
Error Message
"NetworkError: 500 Server Error - http://localhost:7474/db/data/cypher"
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:7474/db/data/cypher. This can be fixed by moving the resource to the same domain or enabling CORS.
When i try from Advance REST Client, it returns correct response. Please refer following code
$(document).ready(function(){
$("#btnQuery").click(function(){
var Request = "{'query' : 'MATCH (Movie { name:{searchName} })-[SHOWS]-(Cinema) RETURN Cinema','params' : {'searchName' : 'Rio 2'}}";
//url = mainURL +"cypher";
url = "http://localhost:7474/db/data/cypher";
$.ajax({
url: url,
headers : {
'Authorization' : 'Bearer 5f0e0d8c2a5477d4a8e79fa2d34f84a'
},
crossDomain: true,
type: 'POST',
dataType: 'application/json',
complete: function(xhr) {
if (xhr.readyState == 4) {
if (xhr.status == 201) {
alert("Data is loaded");
clearUsers();
isUserAdd = false;
}
} else {
alert("Data is not loaded");
}
},
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
data: ('(' + Request + ')')
});
});
});
I have a working example here: http://jexp.github.io/cy2neo
Check out the code: https://github.com/jexp/cy2neo/blob/master/scripts/neo.js#L8
I think the problem was dataType: JSON which caused jquery to send a pre-flight header w/o CORS. I changed it to specifying content-type: JSON
Related
I've seen similar incidents such as this. However, none of them seem to encounter the same problem I am having: Making a POST request and getting a 500 Internal Server Error in response.
I'm attempting to convert either of the following AJAX or XHR that I generated from a postman command to the AngularJS method of using the $http service:
The xhr:
var data = "json=<lots of encoded text>";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://myJenkins.com/job/Ansible_Deploy/build?token=<build_token>");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic <auth data>");
xhr.send(data);
The ajax:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://myJenkins.com/job/Ansible_Deploy/build?token=<build_token>",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"authorization": "Basic <auth data>"
},
"data": {
"json": "<raw json text>"
}
};
$.ajax(settings).done(function (response) {
console.log(response);
});
The broken AngularJS implementation:
var heads = new Headers();
heads.append('Content-Type', 'application/x-www-form-urlencoded');
heads.append('Authorization', 'Basic <auth data>');
$http({
url: "https://myJenkins.com/job/Ansible_Deploy/build?token=<build token>",
method: "POST",
data: <json object>,
headers: heads
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.statusText);
});
Both of the above Ajax and xhr implementations work fine. As mentioned above, the angular approach is giving me a 500 Internal Server Error.
Any ideas why this may be happening? I can provide specifics if they may help, such as information from the network tab on the chrome inspector. Just let me know what I should take a screenshot of and I'll post it here.
EDIT: As promised in the comments, my solution is below.
$http({
url: "https://myJenkins.com/job/Ansible_Deploy/build?token=<build token>",
method: "POST",
data: 'json=' + JSON.stringify(data),
headers: {
'Accept': "*/*",
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic <auth data>'
}
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.statusText);
});
EDIT 2: If you stumble upon this question because you're also getting a 500 Internal Server Error and still don't understand how this was resolved, then it was resolved via a combination of ensuring that CORS was setup on the server containing the endpoint (indicated by Crome's inspector throwing Access-Control-* errors) as well as correctly formatting the x-www-form-urlencoded to be accepted by Jenkins, which requires the data being sent to be of the form json={"parameter":[{"name":<key>, "value":<value>}, ...]}. Furthermore, if the value of an entry is a nested then escaping is required. see this answer for more details.
I am trying to send my selection to a server using post and server need REST, Tested my data with Advanced Rest Client and all works well, But when I try from my chrome extension I am getting undefinded error. Here is what I am trying
chrome.runtime.sendMessage({
method: 'POST',
action: 'REST',
headers: {'Remote-User':'myuser'},
url: 'http://myserver/data/add/',
data: {'content': 'the paste content'}
}, function(responseText) {
alert(responseText);
});
Any help much appreciated, thanks
Update
Based sdc, I changed my code like this and still responseText is undefined :(
function genericOnClick(info, tab)
{
var url = 'http://mysite/data/add/';
var data = $.toJSON({'content': 'the paste content'});
$.ajax({
headers: {
'Remote-User':'username',
'Content-Type':'application/json;charset=utf-8'
},
url: url,
data: data,
method: 'POST',
dataType: 'json',
error: function(xhr, status, error){
alert(xhr.responseText);
},
success: function(data){
console.log('succes: '+data);
}
});
}
I think you misunderstand the purpose of chrome.runtime.sendMessage. See the first two paragraphs of the Message Passing documentation. sendMessage is used for "communication between extensions and their content scripts" it is not designed for sending an HTTP request.
A content script must also "set up a runtime.onMessage event listener to handle the message" only then will you receive a valid response from the sendMessage request
The result from their example is undefined
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
<- undefined
If you are attempting to perform a HTTP request from within your chrome extension, you should use XHR
var data = $.toJSON({'content': 'the paste content'});
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myserver/data/add/", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
xhr.setRequestHeader('Remote-User', 'myuser');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log('xhr response: '+ xhr.responseText);
}
}
xhr.send(data);
I have built a client application, that uses Ajax to call a WebService on another domain (the server supports CORS).
Sometimes when Ajax makes the preflight call, it gets a http error code 400 or 500 from the server, and a response in the format:
{
"httpStatus": 400,
"statusCode": 400
}
I can see the error in the browsers console, but in my JavaScript code, I just get status 0 and statusText "error". Does anyone know how to retrieve the output from the preflight call in JavaScript?
My Ajax call looks lige this:
$.ajax({
type: method,
xhrFields: { withCredentials: true },
url: url,
cache: false,
data: data || '',
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
beforeSend: function(r) {
r.setRequestHeader('Authorization', 'Bearer ' + oauthtoken);
r.setRequestHeader("X-Client-Version", "0.0.1");
}
}).success(function(response) {
console.log("success - service " + url);
callback(response);
}).fail(function(response, textStatus, errorThrown) {
console.log("fail - service " + url);
callback(response);
});
I'm trying to do some searching in Twitter using jQuery. Unfortunately, It's returning only:
https://api.twitter.com/1.1/search/tweets.json?q=django 405 (Method Not Allowed)
XMLHttpRequest cannot load https://api.twitter.com/1.1/search/tweets.json?q=django.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Here's the code:
(function(){
var Twitter = {
init: function(){
this.url = 'https://api.twitter.com/1.1/search/tweets.json?q=django';
this.fetch();
},
fetch: function(){
$.ajax({
url: this.url,
type: 'GET',
dataType: 'json',
success: function(data){ console.log(data); },
error: function(data){ console.log(data); },
beforeSend: this.setHeader
})
},
setHeader: function(xhr){
xhr.setRequestHeader('X-HostCommonName', 'api.twitter.com');
xhr.setRequestHeader('Authorization', 'OAuth my_oauth_data');
xhr.setRequestHeader('Host', 'api.twitter.com');
xhr.setRequestHeader('X-Target-URI', 'https://api.twitter.com');
}
};
Twitter.init();
})();
I've tested the same query with the same headers using REST Console extension for Google Chrome and It worked.
Well, It looks like (here's the info) you can't do OAuth authentication on client side.
So, the only solution here is to code this thing to be invoked on your server.
I'm currently having issues making an external GET request for an API that I need to call and retrieve data from dynamically in JSON. Does anyone know what below may be incorrect? The main issue seems to be that the header information for the Authentication field is not being set correctly and that javaScript can't call out of local domains. I desperately need a work around to this : (error: XMLHttpRequest cannot load http://www.website.com/api.php. Origin http://localhost is not allowed by Access-Control-Allow-Origin.)
function requestDealer(url)
{
alert("looking up dealer");
var request = new XMLHttpRequest();
$.ajax({
url:url,
type: 'GET',
data: null,
Accept : "application/json",
contentType: "application/json",
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
}
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'NLAuth nlauth_account=23984390, nlauth_email = email#email.com, nlauth_signature= myPwrd');
xhr.setRequestHeader('Content-Type', 'application/json');
}