145

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 -->
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
rubdottocom
  • 8,110
  • 10
  • 39
  • 59

7 Answers7

256

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
});
rubdottocom
  • 8,110
  • 10
  • 39
  • 59
  • 20
    I don't think the `crossDomain:true` is required. My understanding is that it's only necessary if you're making a request on your own domain but want jQuery to treat it like a cross-domain request. – Alex W Nov 01 '11 at 23:36
  • 7
    `crossDomain` is not needed. this is a regular `jsonp` request which is meant for cross domain communication. – hitautodestruct Nov 05 '12 at 15:38
  • 52
    I am getting same error, but i want to post the request. jsonp will not support POST. How i can resolve this? – iamjustcoder Jan 23 '13 at 05:57
  • 8
    You also changed your method from POST to GET – Dave Baghdanov Aug 06 '15 at 18:37
  • 5
    @rubdottocom what if url returns xml response instead of json...? – Developer Desk Aug 27 '15 at 11:38
  • I have just added `dataType: 'jsonp'` and it worked brilliantly! – zygimantus Jul 22 '16 at 10:58
  • 4
    Switching to jsonp is not a cure-all. You can't do POST this way, and it won't be dispatched with XHR. – Bobby Feb 10 '17 at 19:53
  • Switching to jsonp is a cure-all! Now I just have to figure out why my XML file is throwing the "Unexpected token <" error! ;) [Because the window builds the json data structure by evaluating the file, and the file is not json. @DeveloperDesk This probably won't work for your purposes if you cannot convert the XML to JSON beforehand.] – Ayelis Jun 06 '17 at 21:59
  • 3
    This no longer works, really frustrating. Still returns "Cross-Origin Read Blocking (CORB) blocked cross-origin response" – theshadow124 Feb 26 '19 at 22:36
  • but you changed from POST to GET – CABascourt Jun 04 '19 at 22:35
42

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

  • 30
    This is very unsafe. If anyone manages to inject javascript into your page, they could easily "phone home" any information a user might provide. – dclowd9901 Oct 05 '14 at 04:33
  • @dclowd9901: *"Unsafe"* is relative depending on the purpose of use and measures observed for setting the *Access-Control-Allow-Origin header* to *anonymous* among other reasons. – nyedidikeke Feb 25 '17 at 23:52
7

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 *;
    }   
}
Mariano Ruiz
  • 4,314
  • 2
  • 38
  • 34
  • 2
    As mentioned above using '*' is very unsafe. – Adaddinsane May 26 '15 at 13:10
  • 6
    Yes, but depending of what are you exposing. If you are publishing a public API without authorization, that's the way (my case). If don't, you shoud be use somethig like this: `Access-Control-Allow-Origin: http://example.com`. – Mariano Ruiz May 26 '15 at 19:41
  • 2
    when i test a api through postman and ajax. but postman request are success. but in ajax return false. – Araf Jan 19 '18 at 19:34
  • @Araf postman and other applications do not trigger CORS protections that are built into browsers. – SenseiHitokiri Dec 12 '18 at 21:23
6

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.

Roope
  • 4,469
  • 2
  • 27
  • 51
Vivek Jain
  • 85
  • 1
  • 1
1

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!

dfox
  • 11
  • 1
1

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");
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

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.

bg17aw
  • 2,818
  • 1
  • 21
  • 27
Prakash
  • 676
  • 6
  • 22