Cross-domain GET request, difference between browser and localhost making the call - javascript

I attempt to make a GET request to an API from a locally hosted meteor app (=> App running at: http://localhost:3000/) and upon doing so I get the error:
"XMLHttpRequest cannot load [the-api-url]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://localhost:3000 is therefore not allowed access."
Yet when I paste [the-api-url] into my browser and hit ENTER, the appropriate API response is shown in my browser window (a little JSON object). I have read some other SO posts about cross-domain request issues, but I don't understand the solutions, or what the difference is between sending the GET from my code or from the browser. Can someone explain why this behavior occurs, and what the appropriate change to my code/design is? My existing code is as below:
$.ajax({
type: "get",
url: auth_ad_act_url,
data: {
ads_token: ACCESS_TOKEN
},
dataType: 'jsonp',
success: function(data, status) {
console.log(data);
}
});
EDIT:
I do a jQuery.ajax() of type "get" supplied with a URL, parameters object, and success callback function, and dataType 'jsonp' to deal with cross-domain requesting.
I posted new code. Now the error is that the response is not correct. (I know this because it worked from my browser, and that responsee lined up with the API documentation). The response is "Resource interpreted as Script but transferred with MIME type text/html: https://host.com/apps/[my-app-id]/authorize_ad_account?callbac…" but it should be an object with the key 'url' and one other thing. I also get the error "Uncaught SyntaxError: Unexpected token :" when I include 'jsonp'. But that incorrect response mentioned above still gets logged to console so I don't understand when that syntax error happens, or where.

The Same Origin Policy does not include what you type into your address bar. If it did, you literally would not be able to access any website at all unless it was saved on your local machine!
In your situation, in order to get the resource that you need from jQuery's get, you'll either need to use a server-side proxy hosted on a matching domain, or since you're consuming JSON see if the API you're using supports JSONP.

There is a possibility to get JSON Data with a cross-domain request. You have to use JSONP and define a callback method, which has to be in the call and in the JSON Data.
Your request:
$.ajax({
type: "GET",
url: auth_ad_act_url + "&callback=?",
jsonpCallback: "jsonCallback",
dataType: "jsonp",
success: function(data) {
// Do something with the data
}
)};
The JSON File on the external server:
jsonCallback(INSERT_HERE_THE_JSON_DATA);
If you do not have the possibility to add the jsonCallback on the external server, check out CORS.

Related

Consume Restful request JSON

When I test the code below it only fails
Any Ideas? The link works fine
$.ajax({
url: 'http://ulacit3352.cloudapp.net/Login/webresources/generic/search/gera',
type: 'GET',
datatype: 'json',
success: function(data) {
alert("works")
},
error: function() {
alert("it does not");
}
});
I get this on Chrome:
The response of the link is not of type "json", instead, it is a plain text, therefore it cannot be parsed. You should change to
dataType: 'text',
Also, for normal ajax, you need to make sure the url is in the same domain of the webpage, which means the code should reside at http://ulacit3352.cloudapp.net/ as well. Otherwise, you should seek for "jsonp" or (better) some server-side solution, such as setting Access-Control-Allow-Origin or make your server as a proxy of the request.
The requested url is server on http which will give rise to This request has been blocked; the content must be served over HTTPS error since the connection is open for eavesdropping and man-in-the-middle (MITM) attacks. It is better to use https provided the url accept https request.
Still there is way to bypass the issue. You can check this LINK

success callback never get invoked for a JSONP request

I have this URL: https://cdn.static.wizzair.com/en-GB/TimeTableAjax?departureIATA=BUD&arrivalIATA=TLV&year=2016&month=6
which returns me a json. if I go to this URL with my browser or if I'm firing the request using a REST client on my browser (DHC) it works! Now, for me with an express server that runs over https, I'm trying to make this request works using jQuery with no luck.
Somehow the error callback is always being executed even though I see in the network debugging that the request was good and seeing the json response!
My code:
/// removed old code ///
$.ajax({
method: 'GET',
url: "https://cdn.static.wizzair.com/en-GB/TimeTableAjax?departureIATA=BUD&arrivalIATA=TLV&year=2016&month=6&callback=?",
dataType: "jsonp",
success: function() { console.log("success"); },
error: function(err) { ;console.log(err); }
});
** * EDIT * **
so I understand this will not work as the target does not support jsonp.
changing it to normal GET request will gets an error and this message:
XMLHttpRequest cannot load https://cdn.static.wizzair.com/en-GB/TimeTableAjax?departureIATA=BUD&arrivalIATA=TLV&year=2016&month=6. The 'Access-Control-Allow-Origin' header has a value 'https://wizzair.com' that is not equal to the supplied origin. Origin 'https://localhost:3000' is therefore not allowed access.
which is expected. But how come this works on my browser and with the locally rest client? What am I doing wrong?
Thanks!
The URL you are requesting is returning JSON, not JSONP.
JSONP requests only work if the server is designed to respond to them with a JSONP formatted response.
For further reading, see What is JSONP all about
Regarding the significant edit to the question: See this duplicate.

JSON Get request using JQuery (cross-domain)

I'm trying to make a simple JSON get request to an API on a domain that I do not control.
My code is simply:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://pubapi.cryptsy.com/api.php?method=marketdatav2',
success: function (data) {
console.log(data);
}
});
});
But since that is a cross-domain request, I am getting this error in the Chrome Console:
XMLHttpRequest cannot load http://pubapi.cryptsy.com/api.php?method=marketdatav2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
And when I try to add the parameter dataType: 'jsonp' the Console returns with this error:
Uncaught SyntaxError: Unexpected token :
But when I examine the Network tab in Chrome I see that under Headers the Status Code is 200 OK and I can actually see the full response in the Response tab, but the console is still showing the "Unexpected Token :" error and the JQuery JSON request is still failing.
Here's the JS Fiddle link: http://jsfiddle.net/6Qcq2/ You can see the same results
I have tried running the url on http://www.hurl.it and it shows me Status OK and the response as well, so I must be doing something wrong.
I've pretty much wasted the whole day trying to figure out how to get around this problem.
Your help is very much appreciated.
The response from the API is JSON, not JSONP, so just changing the data type doesn't help.
You can use a proxy that makes the request and turns the JSON into JSONP:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://jsonp.guffa.com/Proxy.ashx?url=pubapi.cryptsy.com%2fapi.php%3fmethod=marketdatav2',
dataType: 'jsonp',
success: function (data) {
console.log(data);
}
});
});
Demo: http://jsfiddle.net/6Qcq2/1/
You need to setup some type of proxy script. Due to the Same-origin policy, you can't make an ajax call to a resource that is on an external domain. You can get around this by setting up a simple PHP script that will query the data for you. Then, you would point your ajax call to your script (which will be hosted on your domain). The content type for that resource is application/json, so telling jQuery the type is jsonp won't help you.
AJAX requests do not work cross-domain for security reasons. Since you're reading JSON data, you may be able to make JSONP work.
Shouldn't the jsonp response direct to a callback?
What is JSONP all about?

cherrypy/jquery CORS trouble

I've got a simple python web server based on cherrypy. Its resources shall provide an API. THe server has the following code to provide CORS:
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
if __name__ == "__main__":
cherrypy.tools.CORS = cherrypy.Tool('before_finalize', CORS)
cherrypy.quickstart(PyCachedAdmin(), config={'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})
the server is running on localhost:8080. Now I've got a HTML file, available on localhost (default port 80) which loads jquery 1.9. I open the browser console to try the $.ajax to execute any AJAX request to the cherrypy server. I've been trying:
$.ajax({
url:'http://localhost:8080/',
type: "POST",
dataType: "json",
data: {command:"version"}
}).done(function(){
console.log('hej');
});
and
$.ajax({
url:'http://localhost:8080/',
type: "POST",
crossDomain: true,
dataType: "jsonp",
data: {command:"version"}
}).done(function(){
console.log('hej');
});
and
$.support.cors = true
and nothing worked. I'm getting either XMLHttpRequest cannot load http://localhost:8080/. Origin http://localhost is not allowed by Access-Control-Allow-Origin. or GET http://localhost:8080/?callback=jQuery19102827550224028528_1382823727186&command=version&_=1382823727187 404 (Not Found) when using jsonp (it's mysterious that it sends GET instead of POST). There is a few similar questions around, I tried them and these are my results (that something is still wrong).
PS the server is perfectly ok, since all curl tests pass. Something is wrong with the cross-domain stuff.
Are you activating the CORS tool?. You can use the tool by decorating the calling methods or set it on the configuration.
Given that the implementation of PyCachedAdmin is no expressed on the question I might guess that probably you are not enabling the tool, to do so you just need to change the config dictionary and make something like this:
cherrypy.quickstart(PyCachedAdmin(),
config={
'/': {
'request.dispatch':
cherrypy.dispatch.MethodDispatcher(),
'tools.CORS.on': True}})
Or if the methods that you are using on PyCacheAdmin has already been decorated or using _cp_config that extra configuration is not required and this answers will not help you.

Trouble performing simple GET request returning JSON with Javascript

I'm horrible at Javascript, so sorry in advance for what I'm going to go ahead and assume is an amazingly stupid question.
I'm simply trying to perform a GET request to GitHub's public repo API for a given user, and return the value as JSON.
Here's the function I'm trying to use:
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'json',
type: 'get',
success: function(data) {
alert('raw data: ' + data)
var json_response = $.parseJSON(data);
alert(json_response);
}
});
}
This is returning Null for data. And in the console, I see Failed to load resource: cancelled. I know the URL is correct, because if I run curl on the url, it returns the expected data.
jQuery's ajax function supports JSONP which allows cross-domain requests (which you need because you're trying to request data from github.com from another domain). Just change the dataType from 'json' to 'jsonp';
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'jsonp',
type: 'get',
success: function(data) {
var json_response = data;
alert(data);
}
});
}
UPDATE: It's import to note that the end pint (in this case github.com's API) has to support JSONP for this to work. It's not a guarnateed solution for ANY cross-domain request as pointed out in the comments.
JavaScript is subject to cross-domain restrictions when making requests on a different server.
Well, unless you run your code in the github.com domain, that won't work.
You can use simle ajax only in your domain.
One solution is to create a proxy for it. Make a page on your server that does one thing, gets your requested (out of domain) content with curl, and prints it. Then you call this proxy with ajax.
The XmlHttpRequest object (which $ajax uses) cannot download content from a different domain due to the same origin policy. You would need to use something such as JSONP to be able to do this from a browser.
As the others have said, you cannot execute ajax on a remote domain.
You will need to write a server sided script on your domain (such as php), that will do the dirty work retrieving the information needed from the github domain.
Then, use your ajax to query your server side script for the information.
I know the URL is correct, because if
I run curl on the url, it returns the
expected data.
Use that idea to get your ajax working. Create a proxy page on your site that uses curl to retrieve the data you want, then have your "the_url" variable point to that page on your site. Cross-domain restrictions prevent you from being able to use ajax in the manner you attempted.

Categories

Resources