前端开发利器 http-server

在开发过程中,很多情形下,都需要把项目放在 server 环境下运行。

有时候我们打开一个文档使用 file 协议打开的时候,不能发送 ajax 请求,只能使用http 协议才能请求资源,所以此时我们需要在本地建立一个 http 服务,通过IP加端口号,来访问资源。

http-server 是一个超轻量级的基于 nodejshttp web 服务器,http-server 可以将任何一个文件夹当作服务器的目录供自己使用,完全抛开后台的沉重工程,直接运行你的代码。

当我们想要在服务器运行一些代码,但是又不会配置服务器的时候,就可以使用 http-server 来搞定了。http-server 是一个简单的零配置的命令行 http 服务器,它足够强大便于生产和使用,用于本地测试和开发。

安装/更新

打开 git-bash 输入 npm i http-server -g 就可以安装 http-server了:

npm i http-server -g

参数说明

-p Port to use (defaults to 8080)

-a Address to use (defaults to 0.0.0.0)

-d Show directory listings (defaults to 'True')

-i Display autoIndex (defaults to 'True')

-g or --gzip When enabled (defaults to 'False') it will serve ./public/some-file.js.gzin place of ./public/some-file.js when a gzipped version of the file exists and the request accepts gzip encoding.

-e or --ext Default file extension if none supplied (defaults to 'html')

-s or --silent Suppress log messages from output

--cors Enable CORS via the Access-Control-Allow-Origin header

-o Open browser window after starting the server

-c Set cache time (in seconds) for cache-control max-age header, e.g. -c10 for 10 seconds (defaults to '3600'). To disable caching, use -c-1.

-U or --utc Use UTC time format in log messages.

-P or --proxy Proxies all requests which can't be resolved locally to the given url. e.g.: -P http://someurl.com

-S or --ssl Enable https.

-C or --cert Path to ssl cert file (default: cert.pem).

-K or --key Path to ssl key file (default: key.pem).

-r or --robots Provide a /robots.txt (whose content defaults to 'User-agent: *\nDisallow: /')

-h or --help Print this list and exit.
-p 或者 --port 端口设置,默认是 8080
-a 监听地址设置默认是 0.0.0.0
-d 是否显示文件列表 默认true
-i 显示自动索引 默认true
-g 或者 --gzip 默认false,当文件的gzip版本存在且请求接受gzip编码时,它将服务于./public/some-file.js.gz,而不是./public/some-file.js
-e 或者 --ext 如果没有提供默认文件扩展名(默认为html)
-s 或者 --silent 禁止控制台日志信息输出
–cors 允许跨域资源共享
-o 启动服务后打开默认浏览器
-c 设置缓存cache-control max-age heade存留时间(以秒为单位),示例:-c10是10秒,默认是3600秒,如果要禁用缓存就使用-c-1
-U 或者 --utc 使用 UTC格式,在控制台输出时间信息
-P 或者 --proxy 通过一个 url地址,代理不能通过本地解析的资源

常用操作

  • 若要禁用缓存,请使用如下命令运行:
http-server -c-1
  • 开启跨域cors
http-server --cors
  • 指定端口
http-server -p 9999
  • 启动服务后打开浏览器
http-server -o

—————————— 【正文完】——————————

前端学习交流群,想进来面基的,可以加群: 685486827832485817
Vue学习交流 React学习交流

写在最后: 约定优于配置 —— 软件开发的简约原则

——————————【完】——————————

我的:
个人网站: https://neveryu.github.io/neveryu/
Github: https://github.com/Neveryu
新浪微博: https://weibo.com/Neveryu

更多学习资源请关注我的新浪微博…好吗

猜你喜欢

转载自blog.csdn.net/csdn_yudong/article/details/122224674