将 jQuery Post 发送到 Google API 的 Access-Control-Allow-Origin 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6114436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:25:15  来源:igfitidea点击:

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

jqueryajaxgoogle-apicorsjsonp

提问by rubdottocom

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 serieI receive:

我正在使用 Google Moderator API,但是当我尝试添加新系列时,我收到:

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 :/

我尝试使用和不使用回调参数,我尝试将“Access-Control-Allow-Origin *”添加到标题中。而且我不知道如何在此处使用 $.getJSON(如果适用),因为我必须添加 Authorization 标头,而且如果没有来自 $.ajax 的 beforeCall,我不知道该怎么做:/

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 -->

回答by rubdottocom

I solved the Access-Control-Allow-Origin error modifying the dataType parameter to dataType:'jsonp'and adding a crossDomain:true

我解决了将 dataType 参数修改为dataType:'jsonp'并添加一个crossDomain:true的 Access-Control-Allow-Origin 错误

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

回答by Muhammad Tanweer

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.

我有完全相同的问题,它不是跨域,而是同一个域。我刚刚将此行添加到处理 ajax 请求的 php 文件中。

<?php header('Access-Control-Allow-Origin: *'); ?>

It worked like a charm. Thanks to the poster

它就像一个魅力。感谢海报

回答by Mariano Ruiz

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.

如果您在尝试使用无法Access-Control-Allow-Origin *在该应用程序中添加标头的服务时遇到此错误,但您可以在服务器前面放置一个反向代理,则可以通过标头重写避免该错误。

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 Nginxreverse proxy:

假设应用程序在 8080 端口(www.mydomain.com 的公共域)上运行,并且您将反向代理放在同一主机的 80 端口上,这是Nginx反向代理的配置:

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

回答by Vivek Jain

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

是的,当 jQuery 看到 URL 属于不同的域时,它假定调用是跨域调用,因此crossdomain:true这里不需要。

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

另外,请务必注意,$.ajax如果您的 URL 属于不同的域(跨域)或者您使用的是 JSONP ,则无法进行同步调用。只允许异步调用。

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

注意:如果您在async:false请求中指定 ,则可以同步调用该服务。

回答by Zero

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_developmentto app-developmentit works fine.

我使用app_development.something.com,这里 underscore( _) 子域正在创建 CORS 错误。更改app_developmentapp-development它后工作正常。

回答by dfox

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 *

php 有一些小技巧。它不仅适用于 Google,还适用于您无法控制且无法添加 Access-Control-Allow-Origin * 的任何网站

We need to create PHP-file (ex. getContentFromUrl.php) on our webserver and make a little trick.

我们需要在我们的网络服务器上创建 PHP 文件(例如getContentFromUrl.php)并做一个小技巧。

PHP

PHP

<?php

$ext_url = $_POST['ext_url'];

echo file_get_contents($ext_url);

?>

JS

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
  1. 您的浏览器在 JS 的帮助下将向您的服务器发送请求
  2. 您的服务器将向任何其他服务器发送请求并从另一台服务器(任何网站)获得回复
  3. 您的服务器会将此回复发送给您的 JS

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

我们可以让事件 onClick,把这个事件放在某个按钮上。希望这会有所帮助!