?
This document uses PHP Chinese website manual Release
要提供靜態(tài)文件(如圖像,CSS文件和JavaScript文件),請(qǐng)使用express.static
Express中的內(nèi)置中間件功能。
函數(shù)簽名是:
express.static(root, [options])
root
參數(shù)指定要從中為靜態(tài)資產(chǎn)提供服務(wù)的根目錄。有關(guān)options
參數(shù)的更多信息,請(qǐng)參閱express.static。
例如,使用以下代碼在名為public
的目錄中提供圖像,CSS文件和JavaScript文件:
app.use(express.static('public'))
現(xiàn)在,您可以加載public
目錄中的文件:
http://localhost:3000/images/kitten.jpg http://localhost:3000/css/style.css http://localhost:3000/js/app.js http://localhost:3000/images/bg.png http://localhost:3000/hello.html
Express查找相對(duì)于靜態(tài)目錄的文件,因此靜態(tài)目錄的名稱不是URL的一部分。
要使用多個(gè)靜態(tài)資產(chǎn)目錄,請(qǐng)express.static
多次調(diào)用中間件函數(shù):
app.use(express.static('public'))app.use(express.static('files'))
Express按照您使用express.static
中間件功能設(shè)置靜態(tài)目錄的順序查找文件。
注:為獲得最佳結(jié)果,請(qǐng)使用反向代理緩存來提高服務(wù)靜態(tài)資產(chǎn)的性能。
要為express.static
函數(shù)提供的文件創(chuàng)建虛擬路徑前綴(路徑實(shí)際上不存在于文件系統(tǒng)中),請(qǐng)為靜態(tài)目錄指定一個(gè)裝載路徑,如下所示:
app.use('/static', express.static('public'))
現(xiàn)在,您可以從/static
路徑前綴中加載目錄public
中的文件。
http://localhost:3000/static/images/kitten.jpg http://localhost:3000/static/css/style.css http://localhost:3000/static/js/app.js http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html
但是,您提供給express.static
函數(shù)的路徑是相對(duì)于啟動(dòng)node
過程的目錄。如果您從其他目錄運(yùn)行快速應(yīng)用程序,則使用您想要提供的目錄的絕對(duì)路徑更安全:
app.use('/static', express.static(path.join(__dirname, 'public')))
有關(guān)該serve-static
函數(shù)及其選項(xiàng)的更多詳細(xì)信息,請(qǐng)參閱serve-static。