jQuery ajax request from local file (Origin 'null' not allowed access) - javascript

I am making a jQuery ajax call from a local file which retrieves JSON data from a webserver:
$.ajax({
type: 'GET',
url: 'http://mywebsite.com/data.json',
dataType: 'json',
success: showData
});
and I am getting the following error on chrome:
XMLHttpRequest cannot load http://mywebsite.com/data.json. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
I have read through a lot of other answers which seem to come to the conclusion that you cannot make ajax requests from local files with chrome, so the solutions are:
Host the file making the request on the sever
Run chrome with the "--allow-file-access-from-files" flag
but neither of these options are suitable for me.
However, when I host the JSON data on another site (myjson.com), so that the line in the ajax request reads
url: 'https://api.myjson.com/bins/myfile'
the file loads perfectly and the data is correctly displayed.
Why is the ajax request allowed to 'myjson.com' but not to 'mywebsite.com'?
Edit:
I have the line
Header set Access-Control-Allow-Origin "*"
in my apache2.conf file

What you need to do is create a .htaccess file in your document root and add the following lines to it:
<FilesMatch "\.(json)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
What the above lines do is, they allow Cross origin resource sharing for all domains on .json files thus removing the error.

Related

No 'Access-Control-Allow-Origin' header - Tried all possible solutions

I know this question has been asked a lot before, but I literally tried out everything but I'm still getting this error.
I'm trying to fetch json data through ajax in my index.php file.
I'm running my website through apache2 on an ubuntu server. I have no idea where to go from here.
Exact error:
Failed to load http://localhost:32348/getinfo: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
What I tried:
- Adding this to /etc/apache2/apache2.conf File
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>
- Adding this to in between every <Directory> tag to /etc/apache2/apache2.conf File:
Header set Access-Control-Allow-Origin "*"
- Adding this to my index.php file:
<?php
header('Access-Control-Allow-Origin: *');
?>
- Changing 'json' to 'jsonp', setting crossDomain to true and adding headers to allow origin
function fetchLiveStats() {
$.ajax({
url: api + '/getinfo',
dataType: 'jsonp',
type: 'GET',
crossDomain: true,
headers: {'Access-Control-Allow-Origin': '*'},
success: function(response) {
console.log(response);
},
cache: 'false'
}).done(function(data){
pulseLiveUpdate();
lastStats = data;
currentPage.update();
}).always(function () {
setTimeout(function() {
fetchLiveStats();
}, refreshDelay);
});
}
You need to add the Access-Control-Allow-Origin header to the response from http://localhost:32348/getinfo.
What I tried: - Adding this to /etc/apache2/apache2.conf File
Everything else you've said about your question implies that Apache was hosting the website on port 80, not the one on port 32348. You're changing the wrong server.
A website can't give itself permission to access data that another website will give the owner of the browser.
Changing 'json' to 'jsonp'
Don't use JSONP. It is a dirty hack. (It also requires that http://localhost:32348/getinfo return JSONP, which is almost certainly doesn't).
setting crossDomain to true
That just tells jQuery to not add headers it adds to Same Origin requests in case there is an HTTP redirect to a different origin. This prevents it being a complex request that needs a preflight. Since you aren't requesting a same origin URL in the first place, this does nothing.
adding headers to allow origin
You can't put response headers on the request!
Trying to will turn it into a complex request that requires a preflight, and cause you event more problems.
You need to edit whatever code is responsible for serving http://localhost:32348/getinfo
Don't forget to empty your cache (ipconfig/flushdns) and your browser cache when you try a new update, otherwise, the modifications may not be considered...

Angular 4 No 'Access-Control-Allow-Origin' header is present on the requested resource Bittrex [duplicate]

Json issues with javascript and jquery.
Trying to load some JSON using javascript.
I have it working using:
See it here: http://jsfiddle.net/5pjha/789/
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
$.getJSON(url, function (json) {
alert(JSON.stringify(json.results));
});
But it dosnt work on the following urls, why is this?
https://poloniex.com/public?command=return24hVolume
https://bittrex.com/api/v1/public/getmarkets
https://api.mintpal.com/v1/market/summary/
Are the following urls not correct JSON ?
Thanks
The google's api set the Access-Control-Allow-Origin header to *, so you could access it by cross domain.
While other urls you provided do not, so you will got an error like below:
XMLHttpRequest cannot load https://api.mintpal.com/v1/market/summary/.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://fiddle.jshell.net' is therefore not allowed
access.
I believe the issue is down to whether or not the servers you are requesting your JSON from have cross-origin resource sharing (CORS) enabled.
you can see in the headers from the google service that they set Access-Control-Allow-Origin:* This is not the case for teh other URL's you list.
To get around this you will need some form of proxy so that you can request from a server either on the same domain or a server that enables CORS.
For ajax request to any server, You need to define Access-Control-Allow-Origin header for client. which is absent in given. You need to define origin of XMLHttp request in server who can request.
For more info refer this link

JavaScript - 'No Access Control Allow Origin' header' despite one being present

I have a simple PHP file that performs a MySQL query and returns a result.
At the top of the PHP file, I have this code:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
?>
I know that this is working as if I were to inspect in Chrome, if I look at the request headers that come back in the 'Network' tab I can see the header was set successfully.
Now I make the call from my JavaScript file on another domain using jQuery:
var getMyResults = $.ajax({
url: "http://mydomain.uk/myphpfile.php",
data: {something: "someData"},
dataType: "JSON",
type: "GET"
});
Every single time I run this code from the JavaScript file I get the follow error:
XMLHttpRequest cannot load http://mydomain.uk/myphpfile.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myotherdomaincallingthefile.uk' is therefore not allowed access.
Why is this happening?
There is a redirect going on before you get to the final page, which sends the header, locate it; if it is in .htaccess you can add this to the .htaccess file:
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</ifModule>
or your other option is in your Ajax call to use the final URL, which would supply the headers without any redirects in the way.
After a few hours of investigation I found the issue with the help of t3chguy in the comments.
My AJAX request URL: "http://mydomain.uk/directory"
Correct, working cross origin AJAX: "http://mydomain.uk/directory/"
A single extra "/" fixed the issue.
Why?
With the help of http://redirectcheck.com/ I saw that without the '/' Apache was making a redirect which meant that the cross origin header wasn't present on that initial request, hence the error.

getting json from external source in javascript

Json issues with javascript and jquery.
Trying to load some JSON using javascript.
I have it working using:
See it here: http://jsfiddle.net/5pjha/789/
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
$.getJSON(url, function (json) {
alert(JSON.stringify(json.results));
});
But it dosnt work on the following urls, why is this?
https://poloniex.com/public?command=return24hVolume
https://bittrex.com/api/v1/public/getmarkets
https://api.mintpal.com/v1/market/summary/
Are the following urls not correct JSON ?
Thanks
The google's api set the Access-Control-Allow-Origin header to *, so you could access it by cross domain.
While other urls you provided do not, so you will got an error like below:
XMLHttpRequest cannot load https://api.mintpal.com/v1/market/summary/.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://fiddle.jshell.net' is therefore not allowed
access.
I believe the issue is down to whether or not the servers you are requesting your JSON from have cross-origin resource sharing (CORS) enabled.
you can see in the headers from the google service that they set Access-Control-Allow-Origin:* This is not the case for teh other URL's you list.
To get around this you will need some form of proxy so that you can request from a server either on the same domain or a server that enables CORS.
For ajax request to any server, You need to define Access-Control-Allow-Origin header for client. which is absent in given. You need to define origin of XMLHttp request in server who can request.
For more info refer this link

REST request from app works, but not from javascript

I'm building an app that has to get and set data at a remote web service through requests. When I use the jQuery GET request it works fine, I can request data from the service without any problems, but when I use PUT I get some erros:
OPTIONS http://myurl.com 501 (Unsupported method
('OPTIONS'))
OPTIONS http://myurl.com Origin null is not allowed by Access-Control-Allow-Origin.
I've tried almost anything to get this to work, but it won't work. I've download a chrome app called REST Console, which can make custom REST requests. The strange thing is that I can interact with my server over that app but not through my javascript!
This is the javascript:
$.ajax({
url: 'http://myurl.com',
type: 'PUT',
data: '<time>16:00</time>',
success: function(data) { alert(data); }
});
Could anybody tell me what is going on here?
First ensure you're serving the page that runs the script from a web server, not directly from the file system.
I'm guessing your service at http://myurl.com is at a different host name to the host name your page is being served from? For it to work in this case you need to implement HTTP headers to support Cross Origin Resource Sharing.
Your service at http://myurl.com needs to handle an HTTP OPTIONS request, the response to which should be a set of HTTP headers (with no content) as follows:
Access-Control-Allow-Origin: http://url-of-page-with-javascript/
Optionally you can also specify Access-Control-Allow-Credentials, Access-Control-Allow-Headers and Access-Control-Allow-Methods. See the full specification here.
You'll also need to add the same headers with the same values when your server responds to the PUT request - obviously the content will also be included with this response.

Categories

Resources