将 jQuery Post 发送到 Google API 时出现 Access-Control-Allow-Origin 错误
我读了很多关于“Access-Control-Allow-Origin”错误的内容,但我不明白我必须修复什么:(
我正在使用 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.
我尝试使用和不使用回调参数,我尝试添加 ' Access-Control-Allow-Origin *' 到标头,如果适用,我不知道如何在此处使用 $.getJSON,因为我必须添加 Authorization 标头,并且我不知道如何在没有 beforeCall 的情况下执行此操作。来自 $.ajax :/
黑暗中还有光吗?
这就是代码:
<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 -->
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 -->
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我解决了 Access-Control-Allow-Origin 错误,将 dataType 参数修改为 dataType:'jsonp' 并添加 crossDomain:true
I solved the Access-Control-Allow-Origin error modifying the dataType parameter to dataType:'jsonp' and adding a crossDomain:true
我遇到了完全相同的问题,它不是跨域而是同一域。我刚刚将这一行添加到处理 ajax 请求的 php 文件中。
它就像一个魅力。感谢海报
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.
It worked like a charm. Thanks to the poster
如果您在尝试使用无法在该应用程序中添加标头
Access-Control-Allow-Origin *
的服务时遇到此错误,但您可以在服务器前面放置一个反向代理,通过标头重写可以避免该错误。假设应用程序在端口 8080(公共域 www.mydomain.com)上运行,并且您将反向代理放在同一主机的端口 80 上,这是 Nginx 的配置反向代理:
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:
是的,当 jQuery 看到 URL 属于不同的域时,它会假设该调用是跨域调用,因此这里不需要
crossdomain:true
。另外,需要注意的是,如果您的 URL 属于不同的域(跨域)或者您正在使用 JSONP,则无法使用
$.ajax
进行同步调用。仅允许异步调用。注意:如果您在请求中指定
async:false
,则可以同步调用该服务。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.php 有一个小技巧。它不仅适用于 Google,还适用于您无法控制且无法添加 Access-Control-Allow-Origin 的任何网站 *
我们需要创建 PHP 文件(例如 getContentFromUrl.php )在我们的网络服务器上并做一些小技巧。
PHP
JS
工作原理:
我们可以在Click上创建事件,将此事件放在某个按钮上。
希望这会有所帮助!
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
JS
How it works:
And we can make events onClick, put this event on some button.
Hope this will help!
试试我的代码
在 JavaScript 中
在 PHP 中
try my code
In JavaScript
In PHP
就我而言,子域名导致了问题。以下是
我使用
app_development.something.com
的详细信息,此处下划线(_
) 子域正在创建 CORS 错误。将app_development
更改为app-development
后,它工作正常。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 changingapp_development
toapp-development
it works fine.