簡體   English   中英

XMLHttpRequest 'Access-Control-Allow-Origin' 錯誤

[英]XMLHttpRequest 'Access-Control-Allow-Origin' Error

我正在編寫一個基於 Web 的應用程序,我需要在其中訪問在線托管的 txt 文件並讀取該文件。 我正在使用以下代碼來做到這一點:

var oReq = new XMLHttpRequest();
  oReq.addEventListener("load", function(){
     // parse the file
  }
})
oReq.open("GET","https://bahadorsaket.com/others/ranking.txt");
oReq.send();

我收到此錯誤:

無法加載https://bahadorsaket.com/others/ranking.txt :請求的資源上不存在“Access-Control-Allow-Origin”標頭。 因此,不允許訪問 Origin 'null'。

搜索並閱讀這篇文章后,我嘗試將代碼更改為此。

var oReq = new XMLHttpRequest();
  oReq.addEventListener("load", function(){
     // parse the file
  }
})
oReq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
oReq.open("GET","https://bahadorsaket.com/others/ranking.txt");
oReq.send();

這次我收到了這個錯誤:

無法在“XMLHttpRequest”上執行“setRequestHeader”:對象的狀態必須為 OPENED。

知道如何解決這個問題嗎? 我對這些東西很陌生!!!

雖然不是最好的方法,但您也可以使用代理。

$.ajaxPrefilter( function (options) {
  if (options.crossDomain && jQuery.support.cors) {
    var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
    options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
    //options.url = "http://cors.corsproxy.io/url=" + options.url;
  }
});

$.get(
    'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing',
    function (response) {
        console.log("> ", response);
        $("#viewer").html(response);
});

我過去用過這個,效果很好。

取自這個帖子。

對於特定錯誤:

無法在“XMLHttpRequest”上執行“setRequestHeader”:對象的狀態必須為 OPENED。

這是因為您在調用XMLHttpRequest對象上的open方法之前設置了標頭。 重新排序將修復該特定錯誤:

var oReq = new XMLHttpRequest();
  oReq.addEventListener("load", function(){
     // parse the file
  }
})
oReq.open("GET","https://bahadorsaket.com/others/ranking.txt");
oReq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
oReq.send();

但就像其他人提到的那樣,如果后端服務器未配置為支持 CORS,您可能會面臨其他問題。

暫無
暫無

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

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