問題描述
有什么方法可以在發出請求時捕獲由 Access-Control-Allow-Origin
引起的錯誤?我正在使用 jQuery,并且在 .ajaxError()
中設置的處理程序永遠不會被調用,因為請求永遠不會開始.
Is there any way to catch an error caused by Access-Control-Allow-Origin
when making a request? I'm using jQuery, and the handler set in .ajaxError()
never gets called because the request is never made to begin with.
有什么解決辦法嗎?
推薦答案
對于 CORS 請求,應該觸發 XmlHttpRequest 的 onError 處理程序.如果您有權訪問原始 XmlHttpRequest 對象,請嘗試設置事件處理程序,例如:
For CORS requests, the XmlHttpRequest's onError handler should fire. If you have access to the raw XmlHttpRequest object, try setting an event handler like:
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var url = 'YOUR URL HERE';
var xhr = createCORSRequest('GET', url);
xhr.onerror = function() { alert('error'); };
xhr.onload = function() { alert('success'); };
xhr.send();
注意幾點:
在 CORS 請求中,瀏覽器的 console.log 將顯示一條錯誤消息.但是,您的 JavaScript 代碼無法使用該錯誤消息(我認為這是出于安全原因,我之前曾問過這個問題:是否可以捕獲 CORS 錯誤?).
xhr.status 和 xhr.statusText 沒有在 onError 處理程序中設置,因此對于 CORS 請求失敗的原因,您并沒有任何有用的信息.你只知道它失敗了.
The xhr.status and xhr.statusText aren't set in the onError handler, so you don't really have any useful information as to why the CORS request failed. You only know that it failed.
這篇關于捕獲 XMLHttpRequest 跨域錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!