使用http-server开启一个本地服务器

前言

在写前端页面中,经常会在浏览器运行HTML页面,从本地文件夹中直接打开的一般都是file协议,当代码中存在httphttps的链接时,HTML页面就无法正常打开,为了解决这种情况,需要在在本地开启一个本地的服务器。
本文是利用node.js中的http-server,开启本地服务,步骤如下:

1 下载node.js

官网地址: https://nodejs.org
下载完成后在命令行输入命令$ node -v以及$ npm -v检查版本,确认是否安装成功。

2 下载http-server

在终端输入:
$ npm install http-server -g

3 开启 http-server服务

终端进入目标文件夹,然后在终端输入:

$ http-server -c-1   (⚠️只输入http-server的话,更新了代码后,页面不会同步更新)
Starting up http-server, serving ./
Available on:
  http://127.0.0.1:8080
  http://192.168.8.196:8080
Hit CTRL-C to stop the server

4 关闭 http-server服务

按快捷键CTRL-C
终端显示^Chttp-server stopped.即关闭服务成功。

5. http-server参数

下面还会用到一些启动的参数,如下:

  • -p 端口号 (默认 8080)
  • -a IP 地址 (默认 0.0.0.0)
  • -d 显示目录列表 (默认 ‘True’)
  • -i 显示 autoIndex (默认 ‘True’)
  • -e or --ext 如果没有提供默认的文件扩展名(默认 ‘html’)
  • -s or --silent 禁止日志信息输出
  • --cors 启用 CORS via the Access-Control-Allow-Origin header
  • -o 在开始服务后打开浏览器
  • -c 为 cache-control max-age header 设置Cache time(秒) , e.g. -c10 for 10 seconds (defaults to ‘3600’). 禁用 caching, 则使用 -c-1.
  • -U 或 --utc 使用UTC time 格式化log消息
  • -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 启用 https
  • -C or --cert ssl cert 文件路径 (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: * Disallow: /’)
  • -h or --help 打印以上列表并退出

参考:https://www.cnblogs.com/nolaaaaa/p/9126385.html

官网:https://www.npmjs.com/package/http-server

原文地址:https://www.cnblogs.com/vickylinj/p/12336781.html