若要提供靜態檔案,例如圖片、CSS 檔案和 JavaScript 檔案,請在 Express 中使用內建的 express.static
中間件函式。
函式簽章為
express.static(root, [options])
root
引數指定提供靜態資源的根目錄。如需有關 options
引數的更多資訊,請參閱 express.static。
例如,使用下列程式碼提供名為 public
的目錄中的圖片、CSS 檔案和 JavaScript 檔案
app.use(express.static('public'))
現在,您可以載入 public
目錄中的檔案
https://127.0.0.1:3000/images/kitten.jpg
https://127.0.0.1:3000/css/style.css
https://127.0.0.1:3000/js/app.js
https://127.0.0.1:3000/images/bg.png
https://127.0.0.1:3000/hello.html
若要使用多個靜態資源目錄,請多次呼叫 express.static
中間件函式
app.use(express.static('public'))
app.use(express.static('files'))
Express 依照您使用 express.static
中介軟體函式設定靜態目錄的順序來尋找檔案。
注意:為獲得最佳結果,使用反向代理快取以提升提供靜態資源的效能。
如需為由 express.static
函式提供的檔案建立虛擬路徑前置詞(其中路徑實際上不存在於檔案系統中),請為靜態目錄指定安裝路徑,如下所示
app.use('/static', express.static('public'))
現在,您可以從 /static
路徑前置詞載入 public
目錄中的檔案。
https://127.0.0.1:3000/static/images/kitten.jpg
https://127.0.0.1:3000/static/css/style.css
https://127.0.0.1:3000/static/js/app.js
https://127.0.0.1:3000/static/images/bg.png
https://127.0.0.1:3000/static/hello.html
不過,您提供給 express.static
函式的路徑是相對於您啟動 node
程序的目錄。如果您從另一個目錄執行 express 應用程式,則使用您要提供的目錄的絕對路徑會比較安全
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))
如需有關 serve-static
函式及其選項的更多詳細資料,請參閱 serve-static。