本地文件夹http服务器http-server

本地文件夹http服务器,简单来说,就是使用http访问本地文件夹(local地址),而不是以file://开头,两者的区别就是,前者是本地服务器,后者只是访问本地文件。

为什么要部署本地文件夹http服务器?

可以方便实现跨域和防止跨域(google表现的同源策略)等。

比如,我在进行Vue的实例是,请求了本地文件夹的.json文件,然后则是被浏览器出于安全考虑阻止了跨域请求。

vue-resource.js:1190 Failed to load file:///Users/mac/Downloads/shoppingCart/unit/data/cartData.json: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

安装全局http-server

$ npm install http-server -g
/Users/mac/.node_modules_global/bin/http-server -> /Users/mac/.node_modules_global/lib/node_modules/http-server/bin/http-server
+ http-server@0.10.0
updated 1 package in 8.186s

表示安装成功,快捷方式的路径:/Users/mac/.node_modules_global/bin/http-server
原身路径:/Users/mac/.node_modules_global/lib/node_modules/http-server/bin/http-server

配置环境变量

打开terminal,
$ open .bash_profile

添加路径:

export HTTP_SERVER_HOME=/Users/mac/.node_modules_global/lib/node_modules/http-server
export PATH=$PATH:$HTTP_SERVER_HOME/bin

开始使用

关闭terminal再重新打开,之后进入项目根目录:

$ http-server
Starting up http-server, serving ./public
Available on:
  http://127.0.0.1:8080
  http://172.168.16.121:8080
Hit CTRL-C to stop the server

开启成功,在浏览器中输入两个地址中的任意一个即ok!

原文地址:https://www.cnblogs.com/VitoYi/p/7911780.html