Reputation: 51
I’m trying to run a jQuery request through the Census Bureau API, which has Access-Control-Allow-Origin: "*"
, so it should work from anywhere. But for some pages the presence of the cache buster, e.g. &_=123456789
, results in the error Origin https://... is not allowed by Access-Control-Allow-Origin
. If I set cache: true
, the cache buster goes away and there is no error. Same thing on both Safari and Firefox.
StackOverFlow is one example: open the console from this page and run this script:
var data_request = $.ajax({
url: 'https://api.census.gov/data/2014/acs5',
method: 'GET',
dataType: 'json',
cache: false,
data: { get: 'NAME,B01001_001E', for: 'state:09,23,25,33,44,50' }
})
.done( function (data, textStatus, request) {
window.alert('Success: ' + data[1][0]);
})
.fail( function (request, textStatus, errorThrown) {
window.alert('Failure: ' + request.status + ' ' + errorThrown);
});
It will fail, but if cache
is set to true
, it will run.
Any ideas?
— Andy
Upvotes: 0
Views: 74
Reputation: 5886
This is because of the way the API processes GET
parameters. Allow me to explain further:
Most servers on the internet will treat the query string of a URL (the part after the question mark) as series of keys and values. The key value pairs are normally separated by the &
character. Strictly speaking though, this doesn't have to be the case. A query string can contain any arbitrary data you want. It appears the Census Bureau API works this way. Whilst the query string looks like it could be processed as key value pairs it is actually processed as a single query.
The result of this is that appending &_=00000000
to the end of a querystring makes it invalid and causes the error:
error: unknown predicate variable: '_'
Because error pages on the API don't send the Access-Control-Allow-Origin
header you get the error about making cross-origin requests.
You can get around this by implementing your own cache busting which sticks a random number somewhere in the query that won't affect the results, for example:
https://api.census.gov/data/2014/acs5?get=NAME%2CB01001_001E&for=state%3A09%2C23%2C25%2C33%2C44%2C50&for=634563453546
Upvotes: 1