Javascript 跨域XmlHttpRequest跨域CORS

記一個(gè)問題:

今天從阿里云的OSS服務(wù)里用XMLHttpRequest請(qǐng)求圖片(OSS已經(jīng)配置CORS),結(jié)果卻還是報(bào)CORS錯(cuò)誤

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

排查原因,發(fā)現(xiàn)是CORS安全響應(yīng)頭的問題,沒有匹配上OSS的CORS配置.

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

XMLHttpRequest CORS 擴(kuò)展例子:

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();

本文轉(zhuǎn)載自https://www.cnblogs.com/linqing/p/11195521.html 林清

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容