NodeJS | 基于NodeJS的轻量级静态服务器 http-server

  • Post author:
  • Post category:其他


目的: 如何为 docsify 文档项目找一个方便的静态服务器?使用docker内的还是略显繁琐。



1.http-server 简介

  • 官网: https://www.npmjs.com/package/http-server
  • 源码: https://github.com/http-party/http-server
  • http-server: a simple static HTTP server.

http-server is a simple, zero-configuration command-line static HTTP server. It is powerful enough for production usage, but it’s simple and hackable enough to be used for testing, local development and learning.

我感觉特别适用于测试web,查看pdf图片等。



(1)安装


$ npm install --global http-server

我用的服务器之前安装的版本:

$ node -v
v14.16.1

$ npm -v
6.14.12

$ http-server -v
v0.12.3



2. 使用

开启服务:
$ http-server [path] [options]  # http-server 简称 hs

[path] defaults to ./public if the folder exists, and ./ otherwise.


停止服务 ctrl+C



(1)指定端口 -p

常用参数 -p 指定端口号,默认 8080


$ hs -p 10086

# http-server 简称 hs

打开浏览器,输入 http://ip:10086

在这里插入图片描述



(2) 支持跨域访问 –cors

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



(3) 设置用户名和密码

--username	Username for basic authentication	
--password	Password for basic authentication

测试:


$ hs -p 10086 --username tom --password 123


再打开浏览器,要求输入用户名和密码



(4) Magic Files


index.html

will be served as the default file to any directory requests.


404.html

will be served if a file is not found. This can be used for Single-Page App (SPA) hosting to serve the entry page.



(5) 禁用缓存 -c


-c

Set cache time (in seconds) for cache-control max-age header, e.g. -c10 for 10 seconds. To disable caching, use

-c-1

. 默认 3600


$ http-server -c-1

(⚠️只输入http-server的话,更新了代码后,页面不会同步更新)

感觉这个不好用。

如果显示的是修改前,刷新也不更新,就是缓存太厉害了。强制刷新:

shift+F5

– End –



版权声明:本文为wangjunliang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。