在打开本地文件时出现CORS Error: Cross origin requests are only supported for HTTP,无法加载本地文件。



1.Install NodeJS // Hint: If you're on a Mac, you want to install and use Homebrew for this
(安装NodeJS //提示:如果你在用Mac,可以下载Homebrew来安装这个)
2.Open your favorite terminal emulator
(打开一个你喜欢的终端 cmd, git bash之类的)
3.Install http-server by running:
npm install http-server -g(通过运行
npm install http-server -g安装http-server)4.Start http-server by running:
http-server 'path/to/your/angular/root/directory' -o
(通过运行http-server 'path/to/your/angular/root/directory' -o来运行http-server)That last command — specifically, the
-oflag — should open a browser window at:localhost:8080最后一条命令,特别是其中的-o标志,应该在地址
localhost:8080打开了一个浏览器窗口Your angular app should work now; just type in localhost:8080 in your browser's address bar. Remember that from now on — assuming you've completed steps 1-3 above — anytime you desire a server instance, all you have to do is step 4.
或者你已经安装了python,那么打开cmd,进入存放.html文件的文件夹, 输入
python -m http.server

然后打开一个浏览器,在地址栏输入localhost:8000
就可以了
本文介绍了解决在本地环境中加载文件时遇到的CORS错误的方法,通过使用NodeJS和http-server或Python的http.server模块,创建一个本地服务器,从而绕过浏览器的安全限制。
1046

被折叠的 条评论
为什么被折叠?



