问题描述
我看到以下错误:
Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin
使用此代码:
var http = new getXMLHttpRequestObject();
var url = "http://gdata.youtube.com/action/GetUploadToken";
var sendXML = '<?xml version="1.0"?><entry xmlns="http://www.w3.org/2005/Atom"'+
'xmlns:media="http://search.yahoo.com/mrss/'+
'xmlns:yt="http://gdata.youtube.com/schemas/2007">'+
'<media:group><media:title type="plain">My First API</media:title>'+
'<media:description type="plain">First API</media:description>'+
'<media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People</media:category>'+
'<media:keywords>first, api</media:keywords></media:group></entry>';
http.open("POST", url, true);
http.setRequestHeader("Authorization", "AuthSub token=" + AccessToken);
http.setRequestHeader("X-GData-Key", "key="+ dev_key);
http.setRequestHeader("Content-Type", "application/atom+xml; charset=UTF-8");
http.onreadystatechange = function() {
if(http.readyState == 4) {
alert(http.responseXML);
}
}
http.send(sendXML);
这是什么原因造成的,我该如何解决?
What can cause this, and how do I solve it?
推荐答案
在当前域之外发出 ajax 请求时,Javascript 会受到限制.
Javascript is limited when making ajax requests outside of the current domain.
- 示例 1:您的域是 example.com,您想向 test.com 发出请求 => 您不能.
- 示例 2:您的域是 example.com,您想向 inner.example.com 发出请求 => 您不能.
- 示例 3:您的域是 example.com:80,您想向 example.com:81 发出请求 => 您不能
- EX 4:您的域是 example.com,您想向 example.com 发出请求 => 可以.
出于安全原因,Javascript 受到同源策略"的限制,因此恶意脚本无法联系远程服务器并发送敏感数据.
Javascript is limited by the "same origin policy" for security reasons so that a malicious script cannot contact a remote server and send sensitive data.
jsonp 是使用 javascript 的另一种方式.您发出请求,结果被封装到在客户端运行的回调函数中.这与将新脚本标记链接到 html 的头部部分相同(您知道您可以在此处从与您的域不同的域加载脚本).
但是,要使用 jsonp,必须正确配置服务器.如果不是这种情况,则不能使用 jsonp,并且必须依赖服务器端代理(PHP、ASP 等).有很多与这个主题相关的指南,只需谷歌它!
jsonp is a different way to use javascript. You make a request and results are encapsulated into a callback function which is run in the client. It's the same as linking a new script tag into the head part of your html (you know that you can load scripts from different domains than yours here).
However, to use jsonp the server must be configured properly. If this is not the case you cannot use jsonp and you MUST rely on a server side proxy (PHP, ASP, etc.). There are plenty of guides related to this topic, just google it!
这篇关于为什么我看到“访问控制允许来源不允许来源"?这里有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!