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

Czytałem dużo o błędzie 'Access-Control-Allow-Origin', ale nie rozumiem co mam naprawić: (

Gram z Google Moderator API, ale kiedy próbuję dodać nową serię otrzymuję:

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.

Próbowałem z parametrem zwrotnym i bez niego, próbowałem dodać' Access-Control-Allow-Origin * ' do nagłówka. I nie wiem jak używać $.getJSON tutaj, jeśli aplikować, bo muszę dodać nagłówek autoryzacji i nie wiem jak to zrobić bez beforeCall od $.ajax : /

Jakieś światło dla tej ciemności u. u?

Oto kod:

<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 -->
Author: sideshowbarker, 2011-05-24

7 answers

Rozwiązałem błąd Access-Control-Allow-Origin modyfikując parametr dataType do dataType: 'jsonp' i dodając 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
});
 251
Author: rubdottocom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-25 06:12:45

Miałem dokładnie ten sam problem i nie był to cross domain, ale ta sama domena. Właśnie dodałem tę linię do pliku php, który obsługiwał żądanie ajax.

<?php header('Access-Control-Allow-Origin: *'); ?>
Zadziałało jak czar. Dzięki plakatowi
 42
Author: Muhammad Tanweer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-16 12:40:39

Jeśli masz ten błąd podczas próby użycia usługi, której nie możesz dodać nagłówka Access-Control-Allow-Origin * w tej aplikacji, ale możesz umieścić przed serwerem odwrotne proxy, błędu można uniknąć za pomocą przepisania nagłówka.

Zakładając, że aplikacja działa na porcie 8080 (public domain at www.mydomain.com w tym przypadku, gdy serwer jest ustawiony na port 80, to jest to konfiguracja dla 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 *;
    }   
}
 7
Author: Mariano Ruiz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-16 14:20:34

Tak, w momencie, gdy jQuery widzi, że adres URL należy do innej domeny, zakłada, że wywołanie jest wywołaniem między domenami, więc crossdomain:true nie jest tutaj wymagane.

Należy również pamiętać, że nie można wykonać połączenia synchronicznego z $.ajax, jeśli adres URL należy do innej domeny (cross domain) lub używasz JSONP. Dozwolone są tylko połączenia asynchroniczne.

Uwaga: możesz wywołać usługę synchronicznie, jeśli określisz async:false w swoim żądaniu.

 6
Author: Vivek Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-13 19:53:19

Wypróbuj mój kod W 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);
        });;

W 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");
 1
Author: Yogendra Tomar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-09-07 06:02:25

W moim przypadku nazwa sub domeny powoduje problem. Oto szczegóły

Użyłem app_development.something.com, tutaj underscore (_) sub domena tworzy błąd CORS. Po zmianie app_development na app-development działa dobrze.

 0
Author: Zero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-13 20:40:12

Jest mały hack z php. I działa nie tylko z Google, ale z każdej strony internetowej, którą nie kontrolujesz i nie możesz dodać Access-Control-Allow-Origin *{]}

Musimy utworzyć plik PHP (np. getContentFromUrl.php ) na naszym serwerze i zrób małą sztuczkę.

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

Jak to działa:

  1. twoja przeglądarka za pomocą JS wyśle żądanie na Twój Serwer
  2. Twój serwer wyśle w tym celu należy wysłać zapytanie do dowolnego innego serwera i uzyskać odpowiedź z innego serwera (dowolnej strony internetowej)
  3. Twój serwer wyśle tę odpowiedź do twojego JS

I możemy zrobić zdarzenia onClick, umieścić to wydarzenie na jakimś przycisku. Mam nadzieję, że to pomoże!

 0
Author: dfox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-25 09:51:08