Javascript筆記-跨域xmlhttpRequest跨域Cors


Q.XMLHttpRequest跨域:

記一個問題:

    今天從阿里雲的OSS服務里用XMLHttpRequest請求圖片(OSS已經配置CORS),結果卻還是報CORS錯誤

  然后Chrome啟用Disable Cache 或請求頭里添加"Cache-Control","no-cache"后卻沒有問題了。

  排查原因,發現是CORS安全響應頭的問題,沒有匹配上OSS的CORS配置.

 

  CORS 安全響應頭列表和文檔:https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header

 

XMLHttpRequest CORS 擴展例子:

 

function createCORSRequest(method, url) {
let xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
}
else
{
// CORS not supported.
xhr = null;
}
return xhr;
}

let req = new createCORSRequest('GET', 'https://xunchayun.oss-cn-beijing.aliyuncs.com/3dImage/20190715/9058134a-d375-4f36-8192-906c02576848.jpg');
xhr.setRequestHeader("Cache-Control","no-cache");
req.send();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM