Howto get and post data via jQuery from JIRA REST API? - javascript

We are using JIRA 6.4.5 in our company but I am struggeling fetching data from its API REST interface. I have been trying now for the last couple of days, getting stuck on a cross-domain problem or that I don't know the user credentials so I cannot do any server-side either.
Ideally I am having a jQuery page where the user will use his own credentials/session for querying the JIRA data. The JIRA REST API is located at srv1.mydomain.xyz and I am using srv2.mydomain.xyz as my webserver with my code.
I have read the JIRA REST API Reference.
I have tried various Javascript/jQuery stuff - in the below example I am trying to submit 1h 30minutes to a specific issue:
$.ajax({
url: "https://srv1.mydomain.xyz/rest/api/latest/issue/proj-3/worklog",
dataType: "json",
method: "post",
data: { time: "1h 30m",
comment: "Test" }
}).done(function(data) {
alert("Success");
}).fail(function(jqXHR, textStatus) {
alert("Failed");
});
I get this error:
XMLHttpRequest cannot load
https://srv1.mydomain.xyz/rest/api/latest/issue/proj-3/worklog?time=1h+30m&comment=Test.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://srv2.mydomain.xyz' is therefore not
allowed access. The response had HTTP status code 401.
I then looked more in to this and saw that Atlassian has something called Atlassian Connect so I tried with this:
AJS.$.ajax({
url: "https://srv1.mydomain.xyz/rest/api/latest/issue/proj-3/worklog",
type: "post",
dataType: "json",
contentType: "application/json",
xhrFields: { withCredentials: true },
async: false,
method: "post",
data: { time: "1h 30m",
comment: "Test" }
}).done(function(data) {
alert("Success");
}).fail(function() {
alert("Failed");
});
But I get a similar error:
XMLHttpRequest cannot load
https://srv1.mydomain.xyz/rest/api/latest/issue/proj-3/worklog.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://srv2.mydomain.xyz' is therefore not
allowed access.
I have also looked in to if I could do this server-side from my PHP enabled server in the same domain as the JIRA server but as I don't get the base64 encoded credentials when doing a phpinfo() then I don't think I can use this approach either (and I don't want to prompt the user for credentials).
I am painfully aware that my problem is related to cross-domain protection but I cannot find any examples on how to fix it? It would be great if the JIRA server could set a Access-Control-Allow-Origin for certain hosts but I assume this is not a configuration option (I am not in control of the JIRA server).

This is definitely a cross-domain case. And believe me, it exists for your own protection ; )
The method I use is to send the jQuery request to a server-based processing page, which then authenticates and interracts with the Jira server. In your case, since srv1 and srv2 are under the same domain, srv2 (webserver) can talk to srv1 (Jira) using internal IPs (https://10.50.25.87:8080/rest/api/latest/issue/proj-3/worklog, for example) so the cross-domain issue doesn't apply.

Related

No 'Access-Control-Allow-Origin' header is present on the requested resource in simple html form

why this error is showing in my simple html form, I want to get xml data in my simple form to show news on my webpage, but this error is showing continuously, please help
$.ajax({
type: "GET",
url: "https://news.google.com/rss/search?q=Nigeria&hl=en-PK&gl=PK&ceid=PK:en",
dataType: "xml",
success: function(xml) {
console.log(xml)
}
});
It is up to the server that has the resource to allow cross origin access.
Probably there is API for what you are trying to do. API gets implemented by the resource owner and provides controlled access.
Or you can use RSS if there is one.
What you could potentially do is run your requests through a CORS proxy. For example:
$.ajax({
type: "GET",
url: "https://cors-anywhere.herokuapp.com/https://news.google.com/rss/search?q=Nigeria&hl=en-PK&gl=PK&ceid=PK:en",
dataType: "xml",
success: function(xml) {
console.log(xml)
}
});
You can see that this works by simply pasting this code snippet into the console.
This essentially bypasses the CORS issues for you. I would only recommend using this hosted version if you don't have a lot of traffic, otherwise you should host your own version of the CORS proxy.
This is because of CORS(Cross Origin Resource Sharing) policy implemented by browsers. Which means browsers doesn't allow certain requests to be sent from a domain to another domain. However this is not applicable to all type of requests.
Check this link to understand what all requests come under this policy
Inorder to make this work , the other server, in your case https://news.google.com, have to setup in such a way that it allows cross domain requests. This is achieved by servers telling the browser that it is ready to accept cross domain requests from your domain, by adding certain cors related headers. One such is Access-Control-Allow-Origin. But I am afraid you can't do it since you aren't the one managing this server.
Work-Around
Use your backend to send the request to google. So that your xhr request calls your server and your server calls google. No browser No Cors.
xhr---> yourdomain.com/news/get---> someotherdomain.com/news/get

Javascript/JQuery Send custom header in OPTIONS Preflight API

Code dump:
$.ajax({
type: 'GET',
dataType: 'json',
url: api,
xhrFields: {
withCredentials: true
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "Basic [my auth token]");
},
success: function(jd) {
console.log(jd.stringify());
}
});
The problem is that Chrome and Firefox send an OPTIONS preflight when I include a beforeSend, however that OPTIONS request is refused by the API because it doesn't know how to handle an OPTIONS request and treats it like a GET, sees no Authorization header and refuses the request.
The only way I can get this to work is to coerce the browser either to not send an OPTIONS request or include my header with it. I am unable to modify the API that I am using.
I would appreciate it if anyone could advise me.
The reason why browser sends preflight request is that you are using custom headers. Please. read about how to avoid preflight request (content type should be text or html and no custom headers)
If you could not chagne server side the last chance to make it work is to create your custom proxy (for example you can create node server and that node app would take your requests and forward them to those Api Then you will have you own server even in the some domain and this proxy server will send CORS requests to another server domain.

How to set up CORS in an AJAX request

I have been working on a personal webapp and have hit a little snag. My API calls only work for some APIs and not for others. For the ones it doesn't work with I will usually get an error message like so.
XMLHttpRequest cannot load https://api.meetup.com/2/cities. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
After doing some research I know it is to do with CORS not being setup. I was wondering if it would be possible to set this up in the client when making an AJAX request. The current way I am doing this is like so
var handleRequest = function(request){
$.ajax({
type: "GET",
url: request,
success: function(data) {
var rawJSON = JSON.stringify(data, null, 2);
editor.setValue(rawJSON);
},
dataType: 'json'
});
The server you're trying to access has to grant you permission to access it. An IT admin has to provide you with a URL that grants you permission to hit their external server. The server you are trying to hit has to setup CORS. http://enable-cors.org/
According to their docs they support JSONP.
https://www.meetup.com/meetup_api/
This is your way around CORS.

Mailchimp how to call mailchimp 3.0 API in javascript

I am trying to subscribe an email to a list on mailchimp, I followed the documentation first, made a request using "Postman" added what was needed and everything works just fine, so I tried to do it on my website and it didn't work
I tried to made a simple request with the same values I set on postman, but everytime I try to send the request the response says
XMLHttpRequest cannot load
https://us12.api.mailchimp.com/3.0/lists/xxxxxx/members. Response
to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://mywebsite.com' is therefore not allowed
access. The response had HTTP status code 501.
I tried to find a way to overcome this but it has been impossible
I searched on stackoverflow everybody says to use jsonp or add something to the ajax call or use a mailchimp ajax plugin nothing has worked
I tried diferent stackoverflow posts like this one
Mailchimp subscribe using jQuery AJAX?
but almost all of them say the same
I tried cache: false dataType:jsonp crossDomain: true xhrFields: {withCredentials: true}
Here it is my code, I am using Jquery
$.ajax({
type: "POST",
url: "https://usxx.api.mailchimp.com/3.0/lists/xxxxxxxx/members",
data: { "email_address":email#adress.com, "status":"subscribed"},
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==",
"Content-Type": "application/json"
},
success: function(data){
alert('Thanks for subscribing');
},
error: function(data){
alert('there was an error, try again later');
}
});
I also Thought on creating my own api and then make the call to mailchimp api but I might ran into the same problem
Do you have any suggestions?
Thanks in advance
As charliefl noted, this is a CORS issue. MailChimp doesn't support CORS, mostly because it would require you passing your API credentials to the user of the webpage, allowing them to takeover your entire account.
Your two options for MailChimp are to proxy your requests through a server or, for signing people up to your list, you can build a custom signup form that uses a much more restricted API. The caveat of this second method is that it forces all of your subscribes through MailChimp's double opt-in process.

consuming PHP service returning valid json with $.ajax

I've been stuck on consuming a web service created in PHP, not sure what I'm doing wrong.. Ive created a fiddle example here : http://jsfiddle.net/e97AV/
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error.. in the browser when I visit the url it is returning valid json
My question is how would I know when to use jsonp or json? Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
heres the ajax code
baseUrl = "http://exclusivegetaways.co.za/api.php";
$.ajax({
type: "GET",
url: baseUrl,
data: {something : "something"},
//contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("works");
alert(result);
},
error: function (a,b,cc) {
alert(a+b+cc);
}
});
I've since been able to pull json data from the ajax error object?? like so:
baseUrl = "http://exclusivegetaways.co.za/api.php?something=something";
$.ajax({
type: "GET",
url: baseUrl,
dataType: "json",
success: function (res) {
alert("worked");
//alert(res);
},
error: function(jqxhr) {
try {
f = JSON.parse(jqxhr.responseText);
...valid json returned here
} catch(err) {alert(err);}
}
});
This is because of a security restriction that prevents Ajax from querying remote locations.
As a workaround to enable access to a remote location via Ajax, you could build a custom URL in your webApp (in PHP for instance) which queries the distant API and returns JSON.
Then, in your JavaScript, you call this URL (from your application) via Ajax.
First: Always look at your JavaScript error console.
XMLHttpRequest cannot load http://exclusivegetaways.co.za/api.php?location=provinces.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://fiddle.jshell.net' is therefore not allowed access.
See also Ways to circumvent the same-origin policy
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error. in the browser when I visit the url it is returning valid json
This suggests that:
They don't support JSONP
They look at the HTTP headers and 404 your request to block access from Ajax (this isn't a good way to do that, the error code is misleading)
My question is how would I know when to use jsonp or json?
Usually by reading the documentation for the server you are trying to use
Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
Usually by working with whatever support is provided by the API provider (i.e. start with their documentation, then fall back to whatever means they provide for communicating with a human).
Due to Same Origin Policy your ajax request is allowed only if:
domain name, application layer protocol, and (in most browsers) port
number of the HTML document running the script are the same
In your case the application layer protocol is different, that's why your script fails.
Possible solutions are:
JSONP, which has to be provided by the server
CORS, which is a more 'elegant' and clean solution, but is not yet fully supported by IE (IE7 doesn't support it, IE8 has some limitations)
Answer taken from this link

Categories