I read a lot for the \'Access-Control-Allow-Origin\' error, but I don\'t understand what I have to fix :(
I\'m playing with Google Moderator API, but when I try to a
try my code In JavaScript
var settings = {
"url": "https://myinboxhub.co.in/example",
"method": "GET",
"timeout": 0,
"headers": {},
};
$.ajax(settings).done(function (response) {
console.log(response);
if (response.auth) {
console.log('on success');
}
}).fail(function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === '(failed)net::ERR_INTERNET_DISCONNECTED') {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 413) {
msg = 'Image size is too large.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 405) {
msg = 'Image size is too large.';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
});;
In PHP
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
I solved the Access-Control-Allow-Origin error modifying the dataType parameter to dataType:'jsonp' and adding a crossDomain:true
$.ajax({
url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
data: myData,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
There is a little hack with php. And it works not only with Google, but with any website you don't control and can't add Access-Control-Allow-Origin *
We need to create PHP-file (ex. getContentFromUrl.php) on our webserver and make a little trick.
PHP
<?php
$ext_url = $_POST['ext_url'];
echo file_get_contents($ext_url);
?>
JS
$.ajax({
method: 'POST',
url: 'getContentFromUrl.php', // link to your PHP file
data: {
// url where our server will send request which can't be done by AJAX
'ext_url': 'https://stackoverflow.com/questions/6114436/access-control-allow-origin-error-sending-a-jquery-post-to-google-apis'
},
success: function(data) {
// we can find any data on external url, cause we've got all page
var $h1 = $(data).find('h1').html();
$('h1').val($h1);
},
error:function() {
console.log('Error');
}
});
How it works:
And we can make events onClick, put this event on some button. Hope this will help!
In my case the sub domain name causes the problem. Here are details
I used app_development.something.com
, here underscore(_
) sub domain is creating CORS error. After changing app_development
to app-development
it works fine.
If you have this error trying to consume a service that you can't add the header Access-Control-Allow-Origin *
in that application, but you can put in front of the server a reverse proxy, the error can avoided with a header rewrite.
Assuming the application is running on the port 8080 (public domain at www.mydomain.com), and you put the reverse proxy in the same host at port 80, this is the configuration for Nginx reverse proxy:
server {
listen 80;
server_name www.mydomain.com;
access_log /var/log/nginx/www.mydomain.com.access.log;
error_log /var/log/nginx/www.mydomain.com.error.log;
location / {
proxy_pass http://127.0.0.1:8080;
add_header Access-Control-Allow-Origin *;
}
}
I had exactly the same issue and it was not cross domain but the same domain. I just added this line to the php file which was handling the ajax request.
<?php header('Access-Control-Allow-Origin: *'); ?>
It worked like a charm. Thanks to the poster