JavaScript - XMLHttpRequest,Access-Control-Allow-Origin错误

Nik*_*Nik 21 javascript xmlhttprequest

我正在尝试将XMLHttpRequest发送到粘贴网站.我正在发送一个包含api所需的所有字段的对象,但我一直在遇到这个问题.我已经阅读了这个问题,我想:

httpReq.setRequestHeader('Access-Control-Allow-Headers', '*');
Run Code Online (Sandbox Code Playgroud)

会解决它,但事实并非如此.有没有人有关于此错误的信息和/或我如何解决它?

这是我的代码:

(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);

}());
Run Code Online (Sandbox Code Playgroud)

这是确切的控制台输出:

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
Run Code Online (Sandbox Code Playgroud)

这是我在常规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
Run Code Online (Sandbox Code Playgroud)

Sac*_*cho 42

我想你已经错过了访问控制的重点.

快速回顾一下CORS存在的原因:由于来自网站的JS代码可以执行XHR,该网站可能会向其他网站发送请求,伪装成您并利用这些网站对您的信任(例如,如果您已登录,则为恶意站点可以尝试提取信息或执行您从未想过的操作) - 这称为CSRF攻击.为了防止这种情况,Web浏览器对您可以发送的XHR有非常严格的限制 - 您通常仅限于您的域,依此类推.

现在,有时一个站点允许其他站点与之联系是有用的 - 提供API或服务的站点(如您尝试访问的站点)将成为主要候选者.开发CORS是为了允许站点A(例如paste.ee)说"我信任站点B,因此您可以将XHR发送给我".这是由站点A在其响应中发送"Access-Control-Allow-Origin"标头指定的.

在您的具体情况下,似乎paste.ee不打算使用CORS.您最好的办法是联系网站所有者,如果您想将paste.ee与浏览器脚本一起使用,请找出原因.或者,您可以尝试使用扩展(那些应具有更高的XHR权限).

  • 我得到了Koy得到的同样的错误,但直到现在我还没有得到解决方案.你能告诉我,我应该在哪里添加标题"Access-Control-Allow-Origin"?它应该在javascript或服务器端? (2认同)