![](/img/trans.png)
[英]error Access to XMLHttpRequest at file from origin has been blocked by CORS policy
[英]JSON request from LOCAL html file to server raises CORS error : Access to XMLHttpRequest at <URL> from origin 'null' has been blocked by CORS policy
我有一個本地 HTML 文件,其中包含對服務器的 JSON HTTP 請求。 盡管該請求在 IE 中有效,但它在 chrome 上失敗並引發錯誤:
CORS 策略已阻止從源“null”訪問“ http://SERVERNAME/QuestionnaireExample/METHODNAME ”處的 XMLHttpRequest :請求的資源上不存在“Access-Control-Allow-Origin”標頭。
引發錯誤的 XMLHTTP 代碼是:
$.support.cors = true;
//upload the questionnaire
$.ajax({
url: 'http://SERVERNAME/QuestionnaireExample/METHODNAME',
type: 'GET',
success: function (result) {
// CODE for success
},
error: function (result) {
// CODE for error
}
});
});
網絡診斷顯示:
Request URL: http://SERVERNAME/QuestionnaireExample/METHODNAME
Request Method: GET
Status Code: 401 Unauthorized
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Accept: */*
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
正如我提到的,在 IE 中,相同的代碼適用於本地文件
$.support.cors = true;
//upload the questionnaire
$.ajax({
url: 'http://SERVERNAME/QuestionnaireExample/METHODNAME',
type: 'GET',
success: function (result) {
// CODE for success
},
error: function (result) {
// CODE for error
}
});
});
瀏覽器根本不允許從本地文件執行 cors 請求。 它必須從網絡服務器運行。 如果你打開一個像“C:\\temp.html”這樣的文件並在那里運行腳本,就會發生這個錯誤。 但是,如果您從“ http://localhost/temp.html ”打開它,則可以允許 cors 請求,前提是接收服務器允許 cors 請求並且您在發送 ajax 請求之前發送 cors 請求。 我不確定你的行 $.support.cors = true; 足以為該特定請求啟用 cors。 可能是這一行在全局范圍內啟用它,但您仍然需要將 cors 標頭附加到 ajax 請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.