so far as I can tell my issue is that my GET request is not authorised. But my attempts to add authorisation in headers or as values in the URL (api key, username, password) are not being successful.
eg.
$.ajax({
type: 'get',
async: false,
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Basic encodedusername:passwordhere');
},
url: "https://api.pingdom.com/api/2.0/checks",
success: function(Data) {
console.log(Data);
},
error: function(Data) {
}
});
Can anyone advise as to correct Javascript syntax for interacting with the Pingdom API? I believe I'm trying to authorize incorrectly Their documentation focuses on PHP which I'm unable to use in this situation.
https://www.pingdom.com/services/api-documentation-rest/#authentication
I don't think it's possible to use the Pingdom API from Javascript in a web browser.
You'll need to use jsonp to get your browser to allow ajax requests across sites, but according to this response it's impossible to set headers in a jsonp request.
Use CORS Anywhere.
I wanted to get a simple jQuery request working that checked the last Pingdom result for our platform. Because of CORS and the need to specify custom headers for authentication, this didn't seem possible.
I didn't want to setup a proxy server for something so simple so I found this answer and was able to use the CORS Anywhere method, which looks something like this:
// Will use the cors-anywhere proxy if jQuery supports it and crossDomain option is passed in.
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
// options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
// Use ajax requests as normal.
$.ajax({
type: 'get',
async: false,
crossDomain: true,
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Basic encodedusername:passwordhere');
},
url: "https://api.pingdom.com/api/2.0/checks",
success: function(Data) {
console.log(Data);
},
error: function(Data) {
}
});
NOTE: Do not use this if you're passing or retrieving confidential information. You should use your own proxy if you're doing that. But if you're just getting public data, like we were, then this should be a nice and clean method to get around the CORS limitation.
Related
Is it possible to call analytics API from javascript with jQuery?
I've been struggling with this for couple of days with no luck. I tried using CORS wich is sending OPTIONS request first which is rejected (405 error). Also tried with jsonp - but from what I read it has to be configured on server side?
Sample code (nothing fancy):
$.ajax({
url: 'https://analytics.algolia.com/1/searches/test/popular',
method: 'GET',
beforeSend: (xhr) => {
xhr.setRequestHeader('X-Algolia-Application-Id', 'sample');
xhr.setRequestHeader('X-Algolia-API-Key', 'sample');
},
success: (response) => {
console.log(response);
}
});
Also tried with crossOrigin: true, and dataType: 'jsonp'.
This API has not been designed to be called from the frontend (and therefore doesn't support CORS). You will need to build a proxy through your backend.
Am I even close to success? I'm trying to use this block of code is jsfiddle to use a PUT request to the API, when using www.hurl.it with the same URL & XML, it succeeds, (woohoo!) but when I try it using this code I have no such luck.
Selecting "RUN" is jsfiddle yields nothing, as in nothing happens at all except the page flashing.
var url = 'https://api.example.com/v1.svc/results/modules/[moduleID]?apikey=[apikey]&source=[source]'
var xmldata = '<ModuleResult><CourseId>JJxblllJXcw1</CourseId><UserId>XaWpNO10m-M1</UserId><Score>100</Score> <Completed>false</Completed><UpdatedAt>2030-04-30T15:36:30</UpdatedAt><Note>JIL</Note></ModuleResult>'
$.ajax({
url: url,
type: 'PUT',
contentType: 'application/XML',
data: xmldata,
success: function(data) {
alert('Load was performed.');
}
});
Any input would be greatly appreciated!
The call wall being completed Cross Origin, the simple proxy prefilter shown below solved my issue.
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
Note:
A public proxy is not known for being extremely secure, whoever controls the proxy can see all of your data being pushed across it, so ensure the data is not sensitive if using a public proxy.
I need to make a POST request to an external server from my webpage using Javascript. The body and response are both json. I can't figure out how to make this call or what tools to use. How do I make this call?
This is what I have so far using jQuery and ajax:
var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxItems":5}}}';
var response = $.ajax({
url: "http://" + environment + "/vizportal/api/web/v1/getViews",
method: "post",
dataType:'json',
data: JSON.stringify(body),
headers: {
'Content-Type': 'text/plain',
'X-XSRF-TOKEN' : XSRFToken,
'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
},
success:function(response){
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
It is throwing a alerts that just says "Status:" and "Error:"
The console says this "XMLHttpRequest cannot load http://[domain]/vizportal/api/web/v1/getViews. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[domain]' is therefore not allowed access. The response had HTTP status code 405."
Are you the owner of the destination of the call? If yes, implement the CORS headers in server-side.
If no, you can fiddle using JSONP (it bypasses CORS) or you can even implement a server-side proxy that you own to route external requests (and of course, implement CORS there).
Check out the article on CORS in MDN if you want more information : HTTP access control (CORS) on MDN
You can use JQUERY and AjAX. You can send/get information information to/from your API either by post or get method.
It would be something like that:
$("#ButtonForm").click(function(){
$.ajax({
url:(Your url),
dataType:'json',
type: 'post',
data: yourForm.serialize(),
success:function(response){
** If yout API returns something, you're going to proccess the data here.
}
});
});
Ajax:
http://api.jquery.com/jquery.ajax/
You are violating the so called same-origin-policy here. Most browsers don't allow a script to access URLs that do not have the same hostname and port than the page where the script is located. This is a very strict security policy and has often been very difficult to overcome even for testing purposes.
Traditionally the easiest way to go around this has been to use your own web site as a proxy and forward the request through it to the external server. But if you don't have enough control on your own site to implement such a solution, things have been more complicated. If you search the Internet with "same-origin-policy", you'll find a lot of discussion on the topic and other ideas to solve it.
My first suggestion would be to check the "Access-Control-Allow-Origin" that your error message mentions, though I'm not familiar with it myself. It is related to a new scheme called CORS that has been added to W3C recommendations quite recently (2014), and seems to have a wide support in the newest versions of many browsers. Maybe we developers are finally getting some tools to work with this irritating issue.
When you want to use different domain ajax call then you need to use the JSONP datatype which will allow browser to do cross domain request.
Here is more document for the JSONP : https://learn.jquery.com/ajax/working-with-jsonp/
var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxItems":5}}}';
var response = $.ajax({
url: "http://" + environment + "/vizportal/api/web/v1/getViews",
method: "post",
dataType:'jsonp',
data: JSON.stringify(body),
headers: {
'Content-Type': 'text/plain',
'X-XSRF-TOKEN' : XSRFToken,
'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
},
success:function(response){
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
If you use jquery, use .post, or .ajax, to submit
$.post(url, data, callbackSuccess, callbackError);
more about these methods here http://api.jquery.com/jquery.ajax/
example:
var url = 'http://example.com/path/endpoint';
$.post(url, {name: 'Darlan', lastname: 'Mendonça'}, function(response){
// callback success
}, function(response) {
// callback error
});
Is it possible to connect to ASANA without a backend?
We have a secure folder on a webserver where we'd like to retrieve a task list of a project using only Javascript. Is that possible?
I saw some news from Asana that they support JSON-P through Asana Connect, but it's a bit unclear on how you could set this up from the documentation. Is there any examples available that I haven't found? Or have anyone succesfully set this up earlier?
The preferred way to do this is using CORS (added November 2013) - see this gist for an example of how you can use it. If you're unfamiliar with CORS, it stands for Cross-Origin Resource Sharing, and allows you to make cross-domain requests, given that the headers of the client and server match appropriately.
Incase anyone is already using Jquery (like I am) you can use the following code to do the same as the example from #agnoster.
$.ajax({
url : 'https://app.asana.com/api/1.0/users/me',
dataType : 'json',
type: 'GET',
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(api_key + ":"));
}
}).done(function(response) {
console.log(response.data);
});
And if you need to POST/PUT you can use jQuery like this:
$.ajax({
url : https://app.asana.com/api/1.0/tasks/taskid',
dataType : 'json',
type: 'PUT',
data: { "completed": true },
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(api_key + ":"));
}
});
PS! you'll not be able to get this working for IE9 as it does not support sending headers (so the xhr.setRequestHeader() won't work)
I know that the issue already was discussed a lot. I went through the whole bunch of other SO's questions, but still has no solution.
My test case is very simple.
Requirements
I need to get authorised on httpbin.org site from my local server (localhost:63342). Basically I use http://httpbin.org/basic-auth/user/passwd to test HTTP Basic Auth.
I test Basic HTTP Authentication via jQuery.ajax function using GET request.
I need to get this done using exactly REST because actually my real goal is to get authorised via REST API request on teamcity's server which uses GET requests.
What I have done so far
Actually I tried enourmous things (worked with headers(Access-Control-Allow-Credentials, Access-Control-Allow-Origin), tried to use beforeSend function, dealt with jsonP, etc). No luck.
<html>
<head>
<script src="./jquery-1.11.0.js"></script>
</head>
<body>
<div id="target">
Click here
</div>
<script>
$("#target").click(function() {
var username = 'user';
var password = 'passwd';
$.ajax({
type: "GET",
beforeSend: function (xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
},
// I know, this one is redundant
xhrFields: { withCredentials: true },
crossDomain: true,
headers: { 'Access-Control-Allow-Credentials': true },
headers: { 'Access-Control-Allow-Origin': '*' },
// this one is redundant too
headers: { 'Authorization': "Basic " + btoa(username + ":" + password) },
//contentType: "application/json; charset=utf-8",
dataType: 'jsonp',
url: "http://httpbin.org/basic-auth/user/passwd",
success: function(data, textStatus, jqXHR){
alert('success');
},
error: function(jqXHR, textStatus, errorThrown ) {
alert('failure');
},
// I don't know if I have to write it directly or not
username: 'user',
password: 'passwd'
});
});
</script>
</body>
</html>
Results I get
During all my tests I got different results. The code above causes httpbin to show auth popup window to type credentials (it's weird because I send user/pass pair in headers). Another results I've got were: UNAUTHORIZED status (which is quite understandable), "error" error message (which is meaninless), etc...
Experts of jQuery and cross-domain requesting, please help to figure out what should be done here.
P.S. I know this is highly related to CORS issue, but I tried to set Access-Control-Allow-Origin in different ways without any success.
Update:
Actually my initial goal is to be able to invoke CI job from JS code (TeamCity job via REST API using Basic HTTP AUthentication).
So, for TeamCity I believe there is a bug there (in REST API Plugin) - anyone who is interested in, please track the issue TeamCity's REST API Plugin doesn't allow to authenticate using Basic HTTP Authentication
Regarding httpbin.org - test is invalid at all.
Thanks a lot!