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