Case Sensitive URL Triggering CORS Error - javascript

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.

Related

What is the difference between getJSON() function and post() function when make a request across domain?

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

Cross Domain JSON - does it matter what server provides source? [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 3 years ago.
I've found simple tutorial how to make cross domain json call here
And it works perfectly fine, so i decided to use this example, just change url from:
var url = "http://api.myjson.com/bins/23xvb";
to
var url = "http://dl.sniper.pl/test.json"
Unfortunately changing it returns such an error (in chrome):
XMLHttpRequest cannot load http://dl.sniper.pl/test.json. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
Googling that error didnt provide any answers to find a solution so here's the question:
Why i get such an error and how to solve it?
The http://dl.sniper.pl/ server must be configured to send the Access-Control-Allow-Origin response header in responses to requests for http://dl.sniper.pl/test.json.
But because that server isn’t sending the Access-Control-Allow-Origin response header, your browser is refusing to allow your frontend JavaScript code to access that response.
So you either nust configure the http://dl.sniper.pl/ server to send Access-Control-Allow-Origin or else you can make the request through a CORS proxy.
There’s an open CORS proxy you can make you request through by changing your code to this:
var url = "https://cors-anywhere.herokuapp.com/http://dl.sniper.pl/test.json"
That sends the request through the open CORS proxy https://cors-anywhere.herokuapp.com 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 response with the Access-Control-Allow-Origin response header is what the browser sees, so the browser allows your frontend JavaScript code to actually access the response.
You can also easily set up your own CORS proxy using https://github.com/Rob--W/cors-anywhere/
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS for an explanation of how browsers behave when you send cross-origin requests frontend JavaScript code using XHR or the Fetch API or AJAX methods from JavaScript libraries—and for details about what response headers must be received in order for browsers to allow frontend code to access the responses.
you should configure you server todo this in your htaccess
u need something like this
<RequireAll>
Require all granted
</RequireAll>

What is wrong with my HTTP over AJAX (javascript)

My code:
var answer_array = [];
var req = new XMLHttpRequest();
req.onload = function() {
answer_array = answer_array.concat(JSON.parse(this.responseText).results);
console.log(answer_array);
}
req.open("GET", "https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13");
req.setRequestHeader("authorization", "Basic Base64 encoded credentials");
req.setRequestHeader("cache-control", "no-cache");
req.setRequestHeader("postman-token", "b94725ff-408b-c82e-a985-6c38feb380af");
req.send();
This is what is in my console:
scripts2.js:22 OPTIONS https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13 (anonymous function) # scripts2.js:22
2015-10-21 12:41:09.059 index.html:1 XMLHttpRequest cannot load https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
When I go to the network tab on Chrome I see this:
gpsdata?fromdate=2015-10-13 OPTIONS 405 xhr scripts2.js:22 0 B 452 ms
This error message:
No 'Access-Control-Allow-Origin' header is present on the requested resource
means that you are running into a cross origin permission issue which means that you are trying to access a site that does not permit access from the domain that your page is on. If your page is on your local drive being accessed with a file:// URL, then the first thing you can do is to put it on an actual web server and try it there since file:// URLs have some additional restrictions on them.
If that doesn't work either, then the issue is that the api.comettracker.com site is not allowing access from your particular site.
When I put your code into a jsFiddle and try it there and look at the network trace, what I see there is that the OPTIONS method which is used to pre-flight a cross origin request is being rejected by api.comettracker.com which tells the browser the cross origin request as currently formatted is not permitted.
I get a different error if your custom headers are removed from the request so I think that there's something incorrect about your custom headers. Since I don't know that particular API, don't have your access credentials or know how to use them, I don't know what exactly to suggest for the headers, but I think that's the place to start.

jquery json error, when i want to get json from steam market

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&currency=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&currency=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

Testing server's response

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

Categories