在前端开发人员做开发时,当进入到和后台 API 联调阶段时,不可避免会遇到 CORS 错误。 本文介绍一个 Chrome 扩展,可以用来在开发阶段避免 CORS 问题。 注意,这个扩展不能用于生产用途,以免引起 security issue. Chrome 扩展地址: 我写了一段简单的 AJAX JavaScript 调用,来产生 CORS 错误: <html><script>function createXHR () { var XHR = [ function () { return new XMLHttpRequest () }, function () { return new ActiveXObject ("Msxml2.XMLHTTP") }, function () { return new ActiveXObject ("Msxml3.XMLHTTP") }, function () { return new ActiveXObject ("Microsoft.XMLHTTP") } ]; var xhr = null; for (var i = 0; i < XHR.length; i ++) { try { xhr = XHR[i](); } catch(e) { continue } break; } return xhr; }var xhr = createXHR(); xhr.open("GET", "http://localhost:3002/", false); xhr.send(null); console.log(xhr.responseText); </script></html> 本地用 Chrome 打开该网页,会遇到预料中的 CORS 错误: Access to XMLHttpRequest at 'http://localhost:3002/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 安装完扩展之后,在设置页面里,将 Access-Control-Allow-Origin 设置为 * 即可: 浏览器工具栏上,看到 on 的图标,刷新网页,AJAX 调用就能正常执行了: |
|
来自: 汪子熙 > 《JavaScript》