crossdomain.xml configuration - javascript

I have to call to a web service from javascript using ajax:
$.ajax({
type: "GET",
url: "http://[REMOTE-SERVER-IP]:8080/api/service",
contentType: "application/jsonp",
crossDomain: true,
success: successFunc,
error: errorFunc
});
I read that to grant access to the method, a "crossdomain.xml" must be created in the server http://[REMOTE-SERVER-IP]:8080/crossdomain.xml:
<cross-domain-policy>
<allow-access-from domain="[SERVICE-CALLER-IP]"/>
</cross-domain-policy>
But after doing that, when I try to call to the method, I'm getting this error from the javascript debugger:
XMLHttpRequest cannot load http://[REMOTE-SERVER-IP]:8080/[URL]. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin
What am I doing bad?
Thank you very much!!!

You can prefer two options here and both assumes that you can access the server.
The first option is to add callback=? parameter to request url, and modify the server response. Server should add the callback function to the response in the following format
callback_function_coming_from_url([your_server_response])
The second option is to add Access-Control-Allow-Origin: * header to your server response. Or you can specify the address like Access-Control-Allow-Origin: [your_client_address]
I prefer to option 2 since it is the convenient way to accomplish your task, and also, you can control your server response, much more secure than the option 1.
You can get additional info from CORS

Related

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.

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

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.

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

Chrome shows Access Control Allow Origin error

I'm using jquery to post data to a server, the server received the data, but the chrome still shows the error :
XMLHttpRequest cannot load `myServer:63373/api/sendData`. Origin `myServer:63385` is not allowed by Access-Control-Allow-Origin.
Here is my js code:
$.ajax({
type: 'POST',
url: 'myServer:63373/api/SendData',
crossdomain: true,
async: true,
data: myData,
dataType: 'json',
success: function(){ alert('success'); }
});
The strange thing is that the 'success' shows up after the request, and the server did receive the data, but then the error message shows up in the console. Is there any way to avoid this message?
Thanks for all you answers above but I think I've found the way, before I solve this I was trying to use two ways, Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method
with the 87 votes and 32 votes, I found the answers at two different places, and both applied them, but it didn't work. Early this week, I tried to delete the code in the web.config and just left the code in C#, it works! Can't believe these two solutions have confliction.
Anyway, hope this could help others.
"not allowed by Access-Control-Allow-Origin" is the reason. Put simply, you can't normally do an XHR call to a different domain/port/protocol from those of the webpage your javascript was included into.
Modern browsers allow you work around this with permission from the server administrator.
You make your Ajax request with the XHR2 API (http://www.html5rocks.com/en/tutorials/cors/)
The on the server side, you need to emit the following headers to allow access from the domain that served the page that included your javascript:
Access-Control-Allow-Origin: http://your-page-domain.com
Access-Control-Allow-Credentials: true
if situation are
your script is hosted on another server
or subdomain
or try to hit url with another port
this is cross-domian request. jquery can not fulfill cross-domain request.
if this is your issue , then you should use jsonp for this "jsonp " allows cross domain request.
try to do this with using jsonp.
for jsonp every call has a callback means there will be a value in url
and you have to send respnse with this call back in php
means try this:-
$.ajax({
type: 'POST',
url: 'myServer:63373/api/SendData',
crossdomain: true,
async: true,
data: myData,
dataType: 'jsonp',
success: function(){ alert('success'); }
});
and in php
wrap your response in $_GET['_callback']."(".$response.")"; and echo it
you will get response in json .

jQuery check external link

Using Javascript or jQuery, how can I check if an external link is available?
An $.ajax() call is not available as it violates SOP (same problem as here). I have read about JSONP, but I would like to know if there is a more straight solution, as I don't want to load any data from the external server; what I need is only to check if it is reachable.
EDIT (answer)
I solved it with the following code:
$.ajax({url: 'http://www.example.com',
type: 'GET',
dataType: 'jsonp',
complete: function(jqXHR, textStatus) {
console.log(jqXHR.status); // '200' = url reachable
},
timeout: 2000
});
The only problem now is that I get a Parse error, but in any case it can be checked if the external link is working.
You could use YQL to check if a URL is available via its JSONP interface.
YQL Console.
Do you have access to server side languages? You could use AJAX to call a local file which uses something like PHP to check the external address.
If you need help with the PHP part, have a look at http://www.catswhocode.com/blog/amazing-things-to-do-with-php-and-curl
Yes, in browsers that support flash you can use this plugin. It has the same api as native xhr. Further if there is no flash plugin in browsers you still can access the other domain. In some browsers if your target domain response has the following headers there will not be an error.
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, *
Replace * with appropriate domains.
All above techniques are applicable only if the second domain is under your control. If not then you have to use a proxy as Jleagle said.

Categories