JavaScript external API calls - javascript

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');
}

Related

Convert AJAX or XHR POST request to AngularJS $http POST request

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.

Sending data over chrome extension to REST

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

Cross-Origin Request Blocked in Neo4j API

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

405 Error when I'm trying to search in twitter

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.

Adding basic http authorization in a ajax json script

Not really sure how to add authentication in an ajax call for JSON information. I am trying to follow the examples given http://domainapi.com/documentation/how-to-use-domainapi/servuces-provided/domain-availability-api.html to check the availability of a domain name, however it keeps doing a http form pop up asking for username and password.
I thought I had everything right in my code:
function domainAvailabilityCheck(domain) {
$.ajax({
type: 'GET',
url: 'http://api.domainapi.com/v1/availability/'+domain+'.com',
beforeSend: setHeader,
success: function(spitback) {
console.log(spitback.content.domainList.status);
},
dataType:'jsonp'
});
}
var setHeader = function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic YWtpcmF0ZXN0OmR0d3N0ZXN0');
}
Not sure what it is that I am doing wrong.
Your beforeSend isn't allowing Jquery to pass in the xhr object for the header modifications. The line should be
beforeSend: function(xhr) { xhr.setRequest(......); } // all-in-one, no extra function needed
or
beforeSend: function(xhr) { setHeader(xhr); } // call your separate function
you may also:
var setHeader = function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic YWtpcmF0ZXN0OmR0d3N0ZXN0');
}
function domainAvailabilityCheck(domain) {
$.ajax({
type: 'GET',
url: 'http://api.domainapi.com/v1/availability/'+domain+'.com',
beforeSend: setHeader,
success: function(spitback) {
console.log(spitback.content.domainList.status);
},
dataType:'jsonp'
});
}
actually it doesn't matter where to put the variable setHeader which holds the anonymous function, but this way up it's more readable (for me and my soft-compiler ... ;)

Categories