介绍一个能避免 CORS 错误的 Chrome 扩展 - Moe
2021-12-08 本文已影响0人
华山令狐冲
在前端开发人员做开发时,当进入到和后台 API 联调阶段时,不可避免会遇到 CORS 错误。
![](https://img.haomeiwen.com/i2085791/18fc0a8d3c608b55.png)
本文介绍一个 Chrome 扩展,可以用来在开发阶段避免 CORS 问题。
注意,这个扩展不能用于生产用途,以免引起 security issue.
Chrome 扩展地址:
![](https://img.haomeiwen.com/i2085791/d76f954fd284d7cf.png)
我写了一段简单的 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.
![]()
![](https://img.haomeiwen.com/i2085791/dcc74f5238b3a327.png)
![](https://img.haomeiwen.com/i2085791/e6af26224acb918c.png)
安装完扩展之后,在设置页面里,将 Access-Control-Allow-Origin 设置为 * 即可:
![](https://img.haomeiwen.com/i2085791/c77a4509c8e74840.png)
浏览器工具栏上,看到 on 的图标,刷新网页,AJAX 调用就能正常执行了:
![](https://img.haomeiwen.com/i2085791/7c3506a4f2b13d23.png)
更多Jerry的原创文章,尽在:"汪子熙":
![](https://img.haomeiwen.com/i2085791/97c4752c0e619c44.png)