为什么我看到“访问控制允许来源不允许来源"?错误在这里? [英] Why am I seeing an "origin is not allowed by Access-Control-Allow-Origin" error here?

查看:46
本文介绍了为什么我看到“访问控制允许来源不允许来源"?错误在这里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到以下错误:

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.

  • Ex 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 等).有很多与此主题相关的指南,只需 google 即可!

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!

这篇关于为什么我看到“访问控制允许来源不允许来源"?错误在这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆