JavaScript-XMLHttpRequest,访问控制允许源错误
我正在尝试向粘贴站点发送XMLHttpRequest。我正在发送一个包含api所需的所有字段的对象,但我一直遇到这个问题。我读过这个问题,我想:JavaScript-XMLHttpRequest,访问控制允许源错误,javascript,xmlhttprequest,Javascript,Xmlhttprequest,我正在尝试向粘贴站点发送XMLHttpRequest。我正在发送一个包含api所需的所有字段的对象,但我一直遇到这个问题。我读过这个问题,我想: httpReq.setRequestHeader('Access-Control-Allow-Headers', '*'); 我会修好的,但没有。是否有人知道有关此错误的任何信息和/或我如何修复它 这是我的密码: (function () { 'use strict'; var httpReq = new XMLHttpReque
httpReq.setRequestHeader('Access-Control-Allow-Headers', '*');
我会修好的,但没有。是否有人知道有关此错误的任何信息和/或我如何修复它
这是我的密码:
(function () {
'use strict';
var httpReq = new XMLHttpRequest();
var url = 'http://paste.ee/api';
var fields = 'key=public&description=test&paste=this is a test paste&format=JSON';
var fields2 = {key: 'public', description: 'test', paste: 'this is a test paste', format: 'JSON'};
httpReq.open('POST', url, true);
console.log('good');
httpReq.setRequestHeader('Access-Control-Allow-Headers', '*');
httpReq.setRequestHeader('Content-type', 'application/ecmascript');
httpReq.setRequestHeader('Access-Control-Allow-Origin', '*');
console.log('ok');
httpReq.onreadystatechange = function () {
console.log('test');
if (httpReq.readyState === 4 && httpReq.status === 'success') {
console.log('test');
alert(httpReq.responseText);
}
};
httpReq.send(fields2);
}());
下面是确切的控制台输出:
good
ok
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:40217' is therefore not allowed access. http://paste.ee/api
XMLHttpRequest cannot load http://paste.ee/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:40217' is therefore not allowed access. index.html:1
test
以下是我在常规Chromium浏览器上进行本地测试时的控制台输出:
good
ok
XMLHttpRequest cannot load http://paste.ee/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. index.html:1
test
我想你错过了访问控制点 简要回顾CORS存在的原因: 由于来自网站的JS代码可以执行XHR,该网站可能会向其他网站发送请求,伪装成您并利用这些网站对您的信任(例如,如果您已登录,恶意网站可能试图提取信息或执行您不想要的操作),这称为CSRF攻击。为了防止这种情况,web浏览器对您可以发送的XHR有非常严格的限制—您通常仅限于您的域,等等 现在,有时允许其他站点与之联系是很有用的——提供API或服务的站点,比如您试图访问的站点,将是主要候选站点。CORS的开发允许站点A(例如,
paste.ee
)说“我信任站点B,所以您可以从它向我发送XHR”。这是由站点A在其响应中发送“Access Control Allow Origin”标题指定的
在您的特定情况下,paste.ee
似乎不需要使用CORS。如果要在浏览器脚本中使用paste.ee,最好联系网站所有者并找出原因。或者,您可以尝试使用扩展(那些扩展应该具有更高的XHR权限)。我也遇到了同样的问题。
服务器日志显示:
DEBUG: <-- origin: null
DEBUG:服务器设置CORS头而不是客户端。所以我应该一起删除头?编辑:删除它们没有任何作用。您使用的是哪台服务器?控制台输出是来自服务器上的实时预览功能(本地服务器),我指的是web服务器?e、 谢谢,这正是我需要知道的。我得到了与Koy相同的错误,但直到现在我还没有得到解决方案。您能告诉我在哪里添加标题“访问控制允许来源”吗??它应该是javascript还是服务器端?如果HTML页面和相关javascript文件是使用“file://”协议加载的,Chrome特别禁止默认情况下的Ajax访问。存在解决方法,但它们与自身的问题相关(通常在安全领域)。Chrome将来自此类代码的所有Ajax访问视为违反CORS。