My code is relatively simple. I have a URL, which is defined before the request is sent, I then have a $.get() request, which I expect to return back a JSON object. The code is below.
var url = "url"; //Removed for clarity
$.get(url, function (data) {
alert("hi");
});
The url being used within the request is correct. I have copied and pasted the code into my browser and I receive the response that I expect from the endpoint.
However when this JQuery code is executed, the callback function is not called and the alert is not fired. Why is this happening?
Edit: Forgot to post the error message I found in the console.
I'm receiving this:
2Initial%20Loan#:1 Access to XMLHttpRequest at
'-snip url-' from
origin 'https://localhost:44358' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.
Will it have anything to do with the GET request not working?
There might be some problem with the url. The syntax specified by you is correct and the same is checked
var url = "https://jsfiddle.net/"; //Removed for clarity
$.get(url, function (data) {
alert("hi");
});
working code
This is a classic example of CORS, which stands for Cross origin resource sharing. Browsers prevent sending AJAX request to domain other than where the javascript file originated from.
As the error message says you have to set 'Access-Control-Allow-Origin' http response header from your server code. Read more about CORS here [enter link description here CORS MDN
Related
I am trying to access a Google Apps Script WebAPI from my website using javascript to pass some value and create an excel file and download it through this API.
I tried 2 following way:
Using POST request with $.post.
My values are many. So, at first, I use a POST request with a body is JSON of list values. Browser rejects API response, because of CORS error.
I researched about CORS to understand it. At some topics, I found a solution is the following second way.
Access to XMLHttpRequest at 'https://script.google.com/macros/s/xxxxxxx' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Using GET request with $.getJSON.
I pass JSON of list values to URL parameter and make GET request. It worked fine.
var url = 'https://script.google.com/macros/s/' + api_id + '/exec?' + request_parameter_string;
$.post(url, payload, function(data, textStatus) {
// Do something
}, 'json');
$.getJSON(url, function(json_result) {
// Do something
})
.fail(function() {
// Do something
});
What I do not understand is why? Why it works with getJSON but not work with post?
I think CORS work with both of GET and POST requests. And I checked the response header with Postman. The headers are the same Access-Control-Allow-Origin →*.
I think have something is different inside getJSON and post functions.
*UPDATE: Update POST CORS error message.
GET requests are not bound by CORS we can host images and static files in CDN which is different from the origin and would help in improving the performance by caching and making parallel requests.
Similarly GET is used for serving ads, trackers and analytics from third party domains as well.
More information about Same Origin Policy and GET is at https://security.stackexchange.com/a/16221/9517
How the browsers identify Other HTTP Verbs are allowed for the cross origin request is elaborated # https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
I am trying to access the JSON metadata corresponding to Python packages in the form http://pypi.python.org/pypi/<package_name>/json using JavaScript.
My code looks something like this:
var name = $('#name').val();
var url = 'http://pypi.python.org/pypi/' + name + '/json';
$.getJSON(url, function(result){
console.log(result);
});
The problem is that the url for the json is case sensitive, so for example, pypi.python.org/pypi/flask/json gets redirected to pypi.python.org/pypi/Flask/json since the package 'Flask' needs to have a capital F.
Thus, if name is flask, I get the error XMLHttpRequest cannot load https://pypi.python.org/pypi/flask/json. Redirect from 'https://pypi.python.org/pypi/flask/json' to 'https://pypi.python.org/pypi/Flask/json' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Any idea on how to properly access the json even if the package name has the wrong capitalization?
If you make the request through an open CORS proxy it should work; try changing your code to:
var url = 'https://cors-anywhere.herokuapp.com/http://pypi.python.org/pypi/'
+ name + '/json';
That sends the request through https://cors-anywhere.herokuapp.com, an open CORS proxy which adds the Access-Control-Allow-Origin response header to it and then passes that back to your requesting frontend code as the response.
That redirect response with the Access-Control-Allow-Origin response header is what the browser sees, so the browser will actually follow the redirect instead of stopping.
All the said, it seems like the pypi.python.org site should really be including the Access-Control-Allow-Origin response header in their 3xx redirect responses, so you might consider filing a bug at https://sourceforge.net/p/pypi/support-requests/ requesting that they do.
I have a problem with ajax request to Steam.
I want to get price from steam market.
function jPrice(httpToJson) {
$.getJSON(httpToJson, function(data) {
return data.median_price;
});
}
When I call function
jPrice('http://steamcommunity.com/market/priceoverview/?country=US¤cy=1&appid=730&market_hash_name=StatTrak%E2%84%A2%20P250%20%7C%20Steel%20Disruption%20%28Factory%20New%29');
I get an error:
XMLHttpRequest cannot load http://steamcommunity.com/market/priceoverview/?country=US¤cy=1&appid=730&market_hash_name=StatTrak%E2%84%A2%20P250%20%7C%20Steel%20Disruption%20%28Factory%20New%29. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://lоcalhоst:63342' is therefore not allowed access.
I try:
Set php header Access-Control-Allow-Origin to *
JSONP
RESULT -> The same thing (error)!
Maybe someone knows a solution to this problem?
You won't be able to get the results in your browser via ajax request made directly against steamcommunity.com, neither by setting the header Access-Control-Allow-Origin to *, nor by sending a JSONP request.
For this to work, steamcommunity.com should either add CORS headers in the response (the error message you're seing means that they are not there), or format the output to be JSON-P. They didn't do either.
This is a browser restriction, do not allow the content from a different origin to be loaded via ajax. What you need to do is introduce a middle-ware, so have your back-end server to make a request against steamcommunity.com and return the same response, and make the ajax call against you're server. This will work, your back-end is sending the request, and as it is not a browser request, the response will land, than your ajax call will be able to get the response as well since it is issued against the same domain
I have a URL, which gives response on browser:
https://api.sandbox.paypal.com/retail/merchant/v1/locations
It gives:
{
"errorCode": 600031,
"message": "Missing access token",
"developerMessage": "You must provide an access token when calling this API. It can be passed as either a header of the form \"Authorization: Bearer \" or as a query parameter called access_token.",
"errorType": "oauth/missing_access_token",
"correlationId": "4de95cd8aa090"
}
I tried this:
$.ajax({
url: "https://api.sandbox.paypal.com/retail/merchant/v1/locations",
dataType: 'json',
type: 'POST',
success: function (data) {
console.log(data);
alert("success", data);
},
error: function (data) {
alert("fail", data);
console.log(data);
alert("Sorry..Please try again later");
},
});
But I am not getting the same response as I am getting on browser. I am getting error.
Please check here
http://jsfiddle.net/ajitksharma/wehGy/
However while debugging on Browser console I got the error:
XMLHttpRequest cannot load https://api.sandbox.paypal.com/retail/merchant/v1/locations. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
You can make AJAX calls to a backend API which is on another domain, however, it needs to return JSONP format and not just JSON, otherwise you get and error. This is due to same origin policy: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy.
This discussion may be helpful to understand JSONP: Can anyone explain what JSONP is, in layman terms?
Since you don't have control over PayPal's API and you can't ask them to return JSONP to you, these requests to PayPal's API need to be done from the server-side script of your application.
Running this from any other location, for example JSFiddle, will give you the Access-Control-Allow-Origin error since you're making a cross-domain request. Please read further about the same-origin policy.
As for the first error, its because your request needs an API key from paypal. See this page about getting an API key and making a simple request.
As Lisa Stoz and kaminari suggested it is not possible to call a service in another domain without some patch work. Now as you see the response when you hit that url via browser it says you need to add an extra header to your ajax request something like 'authorisation'
I have a form in my angular app in which user are required to provide a valid url.
Therefore when submitting the form, I'd like to test if the URL is valid by making a get request to the url provided and check if the server sends 200.
When a click the submit button, the following code is run:
$http.get(scope.target_url).success(function(){
// some code
}).error(function(error){
console.log(error);
});
However, I never get a successfull answer:
- if I provide a url like: 'http://www.somesite.com', I get:
XMLHttpRequest cannot load 'http://www.somesite.com'. Received an invalid response. Origin 'mydomain' is therefore not allowed access.
if I provide a url like: 'http://somesite.com', I get:
XMLHttpRequest cannot load http://somesite.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'mydomain' is therefore not allowed access.
Where does the problem come from?
That is normal security constraints. Read about CORS here:
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing