簡體   English   中英

JavaScript - XMLHttpRequest,Access-Control-Allow-Origin錯誤

[英]JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

我正在嘗試將XMLHttpRequest發送到粘貼網站。 我正在發送一個包含api所需的所有字段的對象,但我一直在遇到這個問題。 我已經閱讀了這個問題,我想:

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

我已經調查過了,當我從本地驅動器調用文件時,發生這種情況並沒有填充。 當我將文件復制到服務器並從服務器上使用它時 - 請求完全正常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM