Express での静的ファイルの提供
画像、CSSファイル、JavaScriptファイルなどの静的ファイルを提供するには、Express で組み込まれているミドルウェア関数「express.static」を使用します。
関数の署名は次のとおりです:
express.static(root, [options]);root 引数は、静的アセットを提供するルートディレクトリを指定します。
For more information on the options argument, see express.static.
例えば、publicという名前のディレクトリに画像、CSSファイル、JavaScriptファイルを表示するには、次のコードを使用します。
app.use(express.static('public'));public ディレクトリにあるファイルを読み込むことができます。
http://localhost:3000/images/kitten.jpghttp://localhost:3000/css/style.csshttp://localhost:3000/js/app.jshttp://localhost:3000/images/bg.pnghttp://localhost:3000/hello.htmlExpress は静的ディレクトリからの相対的なファイルを検索するので、静的ディレクトリ の名前は URL の一部ではありません。
複数の静的アセットディレクトリを使用するには、express.static ミドルウェア関数を複数回呼び出します。
app.use(express.static('public'));app.use(express.static('files'));Express は、express.static ミドルウェア関数で静的ディレクトリを設定する順序でファイルを検索します。
For best results, use a reverse proxy cache to improve performance of serving static assets.
To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:
app.use('/static', express.static('public'));/static というプレフィックスから、 public ディレクトリにあるファイルをロードできます。
http://localhost:3000/static/images/kitten.jpghttp://localhost:3000/static/css/style.csshttp://localhost:3000/static/js/app.jshttp://localhost:3000/static/images/bg.pnghttp://localhost:3000/static/hello.htmlしかし、express.static関数に与えるパスは、nodeプロセスを起動したディレクトリからの相対パスです。 expressアプリを別のディレクトリから実行する場合、提供したいディレクトリの絶対パスを使用する方が安全です: expressアプリを別のディレクトリから実行する場合、提供したいディレクトリの絶対パスを使用する方が安全です:
const path = require('path');app.use('/static', express.static(path.join(__dirname, 'public')));import path from 'path';
app.use('/static', express.static(path.join(__dirname, 'public')));serve-static 関数とそのオプションの詳細については、 serve-static を参照してください。