httpsrv - 簡單的本機 http 伺服器
httpsrv 是一個非常簡單的小型伺服器,功用很像python2
的SimpleHTTPServer
可以透過輸入簡單的一行指令,將某個資料夾作為暫時的 http server,然後就能在瀏覽器上瀏覽
安裝
npm i -g httpsrv
#或 yarn global add httpsrv
使用教學
basic
先使用cd
到你想要的資料夾之後輸入
httpsrv . # . 代表當前資料夾
然後打開瀏覽器到 localhost:3333 應該能看到目前這個目錄下的檔案列表 這張圖片是這個部落格的 hexo 資料夾
port&log
例如這個可以在 localhost:8888 上開啟一個伺服器,並把所有的 request 給記錄在 console 中
httpsrv . -p 8888 -l
其他選項
建議直接到 maple3142/httpsrv 看更完整的
Usage: httpsrv <basedir>
Options:
--help Show help [boolean]
--version Show version number [boolean]
--port, -p Port to listen [number] [default: 3333]
--log, -l Enable logger [boolean]
--cors, -c Access-Control-Allow-Origin header [string]
--fallback, -f A file will be send when 404, useful in SPA [string]
--indexhtml, -i Try to show index.html if exists [boolean]
Examples:
httpsrv . -p 8888 Start server on port 8888
進階使用
blog
這還可以拿來測試 hexo 所建立出來的網站拿目前這個部落格來做範例 GitHub repo
git clone https://github.com/maple3142/Blog.git
cd Blog
npm install
npm run build #一般來說是hexo generate, 不過我有把build增加一些東西(例如minify)
httpsrv public -i -f 404.html
最後一行的-i
是自動在目錄底下偵測有沒有index.html
,有就傳送出來 -f 404.html
是會在找不到檔案(404)時傳送的檔案,還有這邊要注意的是404.html
不能打成public/404.html
WynnStats
WynnStats 是我之前弄的一個 SPA 的練習,打算用它來做為範例
git clone https://github.com/maple3142/WynnStats.git
cd WynnStats
npm install
npm run build
httpsrv dist -i -f index.html
接下來一樣是開啟 localhost:3333,然後隨便點個連結然後 F5 會發現功能都很正常最後一行看起來和上面幾乎一樣,主要是-f index.html
的作用因為 SPA 網站只會有一個index.html
,在 404 時就傳送index.html
就好了, route 的邏輯是在裡面用 javascript 判斷的