NestJs 靜態目錄配置
網上查看了很多文件,發現很多都是自己實現中介軟體來完成此功能,不僅浪費時間,而且增加了太多的程式碼量。實際上,nest已經幫助我們封裝好了相關功能。
1、查詢線索
由於官方文件沒有做詳細解釋說明,那麼我們可以從此框架底層入手:
我們知道,nestjs底層用的是express,那麼express是通過什麼來完成靜態目錄構建的:
serve-static
2、搜尋原始碼
我們在專案搜尋欄目中搜索“serve-static”會發現如下圖:

yarn.lock.png
也就是說,當我們在使用nest框架的時候,serve-static 會隨之而構建好,那麼我們直接參考其原始碼即可: 依賴地址
Nestjs 原始碼:
// Type definitions for serve-static 1.13 // Project: https://github.com/expressjs/serve-static // Definitions by: Uros Smolnik <https://github.com/urossmolnik> //Linus Unnebäck <https://github.com/LinusU> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 /* =================== USAGE =================== import * as serveStatic from "serve-static"; app.use(serveStatic("public/ftp", {"index": ["default.html", "default.htm"]})) =============================================== */ /// <reference types="express-serve-static-core" /> import * as express from "express-serve-static-core"; import * as m from "mime"; /** * Create a new middleware function to serve files from within a given root directory. * The file to serve will be determined by combining req.url with the provided root directory. * When a file is not found, instead of sending a 404 response, this module will instead call next() to move on to the next middleware, allowing for stacking and fall-backs. */ declare function serveStatic(root: string, options?: serveStatic.ServeStaticOptions): express.Handler; declare namespace serveStatic { var mime: typeof m; interface ServeStaticOptions { /** * Enable or disable setting Cache-Control response header, defaults to true. * Disabling this will ignore the immutable and maxAge options. */ cacheControl?: boolean; /** * Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot ("."). * Note this check is done on the path itself without checking if the path actually exists on the disk. * If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when when set to "deny"). * The default value is 'ignore'. * 'allow' No special treatment for dotfiles * 'deny' Send a 403 for any request for a dotfile * 'ignore' Pretend like the dotfile does not exist and call next() */ dotfiles?: string; /** * Enable or disable etag generation, defaults to true. */ etag?: boolean; /** * Set file extension fallbacks. When set, if a file is not found, the given extensions will be added to the file name and search for. * The first that exists will be served. Example: ['html', 'htm']. * The default value is false. */ extensions?: string[]; /** * Let client errors fall-through as unhandled requests, otherwise forward a client error. * The default value is false. */ fallthrough?: boolean; /** * Enable or disable the immutable directive in the Cache-Control response header. * If enabled, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed. */ immutable?: boolean; /** * By default this module will send "index.html" files in response to a request on a directory. * To disable this set false or to supply a new index pass a string or an array in preferred order. */ index?: boolean | string | string[]; /** * Enable or disable Last-Modified header, defaults to true. Uses the file system's last modified value. */ lastModified?: boolean; /** * Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the ms module. */ maxAge?: number | string; /** * Redirect to trailing "/" when the pathname is a dir. Defaults to true. */ redirect?: boolean; /** * Function to set custom headers on response. Alterations to the headers need to occur synchronously. * The function is called as fn(res, path, stat), where the arguments are: * res the response object * path the file path that is being sent * stat the stat object of the file that is being sent */ setHeaders?: (res: express.Response, path: string, stat: any) => any; } function serveStatic(root: string, options?: ServeStaticOptions): express.Handler; } export = serveStatic;
3、使用方式:
說明:原始碼中的註釋說的很清楚用法,由於現階段技術有限,博主將專案目錄作為檔案地址來簡單的使用。
程式碼使用:只需要一句程式碼:
在 main.ts檔案中:
//... import * as serveStatic from 'serve-static'; async function bootstrap() { const app = await NestFactory.create(AppModule); //.... // 使用serve-static // '/public' 是路由名稱,即你訪問的路徑為:host/public // serveStatic 為 serve-static 匯入的中介軟體,其中'../public' 為本專案相對於src目錄的絕對地址 app.use('/public', serveStatic(path.join(__dirname, '../public'), { maxAge: '1d', extensions: ['jpg', 'jpeg', 'png', 'gif'], })); //.... await app.startAllMicroservicesAsync(); await app.listen(9871); } bootstrap();
在專案根目錄下建立public目錄:

目錄建立.png
4、測試效果:
首先使用nestjs自帶的upload api來上傳檔案,這裡不做過多說明,最終通過postman完成測試檔案上傳:

測試上傳.png
再使用瀏覽器瀏覽:

瀏覽圖片.gif