Access-Control-Allow-Origin error sending a jQuery Post to Google API's

JqueryAjaxGoogle ApiCorsJsonp

Jquery Problem Overview


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 add new serie I receive:

XMLHttpRequest cannot load 
https://www.googleapis.com/moderator/v1/series?key=[key]
&data%5Bdescription%5D=Share+and+rank+tips+for+eating+healthily+on+the+cheaps!
&data%5Bname%5D=Eating+Healthy+%26+Cheap
&data%5BvideoSubmissionAllowed%5D=false. 
Origin [my_domain] is not allowed by Access-Control-Allow-Origin.

I tried with and without callback parameter, I tried to add 'Access-Control-Allow-Origin *' to the header. And I don't know how to use $.getJSON here, if apply, because I have to add the Authorization header and I don't know how to do it without beforeCall from $.ajax :/

Any light for this darkness u.u?

That's the code:

<script src="http://www.google.com/jsapi"></script>

<script type="text/javascript">

var scope = "https://www.googleapis.com/auth/moderator";
var token = '';

function create(){
     if (token == '')
      token = doCheck();

     var myData = {
      "data": {
    	"description": "Share and rank tips for eating healthily on the cheaps!", 
    	"name": "Eating Healthy & Cheap", 
    	"videoSubmissionAllowed": false
      }
    };

    $.ajax({

    	url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
    	type: 'POST',
    	callback: '?',
    	data: myData,
    	datatype: 'application/json',
    	success: function() { alert("Success"); },
    	error: function() { alert('Failed!'); },
    	beforeSend: setHeader

    });
}

function setHeader(xhr) {

  xhr.setRequestHeader('Authorization', token);
}

function doLogin(){	
    if (token == ''){
       token = google.accounts.user.login(scope);
	}else{
	   alert('already logged');
	}
}


function doCheck(){				
    token = google.accounts.user.checkLogin(scope);
    return token;
}
</script>
...
...
<div data-role="content">
    <input type="button" value="Login" onclick="doLogin();">
	<input type="button" value="Get data" onclick="getModerator();">
    <input type="button" value="Create" onclick="create();">
</div><!-- /content -->

Jquery Solutions


Solution 1 - Jquery

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
});

Solution 2 - Jquery

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

Solution 3 - Jquery

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 *;
    }   
}

Solution 4 - Jquery

Yes, the moment jQuery sees the URL belongs to a different domain, it assumes that call as a cross domain call, thus crossdomain:true is not required here.

Also, important to note that you cannot make a synchronous call with $.ajax if your URL belongs to a different domain (cross domain) or you are using JSONP. Only async calls are allowed.

Note: you can call the service synchronously if you specify the async:false with your request.

Solution 5 - Jquery

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");

Solution 6 - Jquery

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.

Solution 7 - Jquery

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:

  1. Your browser with the help of JS will send request to your server
  2. Your server will send request to any other server and get reply from another server (any website)
  3. Your server will send this reply to your JS

And we can make events onClick, put this event on some button. Hope this will help!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrubdottocomView Question on Stackoverflow
Solution 1 - JqueryrubdottocomView Answer on Stackoverflow
Solution 2 - JqueryMuhammad TanweerView Answer on Stackoverflow
Solution 3 - JqueryMariano RuizView Answer on Stackoverflow
Solution 4 - JqueryVivek JainView Answer on Stackoverflow
Solution 5 - JqueryYogendra TomarView Answer on Stackoverflow
Solution 6 - JqueryPrakashView Answer on Stackoverflow
Solution 7 - JquerydfoxView Answer on Stackoverflow