最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

NestJs 靜態(tài)目錄配置詳解

 更新時(shí)間:2019年03月12日 08:32:35   作者:stormKid  
這篇文章主要介紹了NestJs 靜態(tài)目錄配置,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

網(wǎng)上查看了很多文檔,發(fā)現(xiàn)很多都是自己實(shí)現(xiàn)中間件來(lái)完成此功能,不僅浪費(fèi)時(shí)間,而且增加了太多的代碼量。實(shí)際上,nest已經(jīng)幫助我們封裝好了相關(guān)功能。

1、查找線索

由于官方文檔沒(méi)有做詳細(xì)解釋說(shuō)明,那么我們可以從此框架底層入手:

我們知道,nestjs底層用的是express,那么express是通過(guò)什么來(lái)完成靜態(tài)目錄構(gòu)建的:

serve-static

2、搜索源碼

我們?cè)陧?xiàng)目搜索欄目中搜索“serve-static”會(huì)發(fā)現(xiàn)如下圖:

也就是說(shuō),當(dāng)我們?cè)谑褂胣est框架的時(shí)候,serve-static 會(huì)隨之而構(gòu)建好,那么我們直接參考其源碼即可:依賴地址

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、使用方式:

說(shuō)明:源碼中的注釋說(shuō)的很清楚用法,由于現(xiàn)階段技術(shù)有限,博主將項(xiàng)目目錄作為文件地址來(lái)簡(jiǎn)單的使用。

代碼使用:只需要一句代碼:

在 main.ts文件中:

 //...
  import * as serveStatic from 'serve-static';
  async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  //....
  // 使用serve-static
  // '/public' 是路由名稱,即你訪問(wèn)的路徑為:host/public
  // serveStatic 為 serve-static 導(dǎo)入的中間件,其中'../public' 為本項(xiàng)目相對(duì)于src目錄的絕對(duì)地址
  app.use('/public', serveStatic(path.join(__dirname, '../public'), {
   maxAge: '1d',
   extensions: ['jpg', 'jpeg', 'png', 'gif'],
  }));
  //....
  await app.startAllMicroservicesAsync();
  await app.listen(9871);
}
bootstrap();

在項(xiàng)目根目錄下創(chuàng)建public目錄:

目錄創(chuàng)建.png

4、測(cè)試效果:

首先使用nestjs自帶的upload api來(lái)上傳文件,這里不做過(guò)多說(shuō)明,最終通過(guò)postman完成測(cè)試文件上傳:

測(cè)試上傳.png

再使用瀏覽器瀏覽:

瀏覽圖片.gif

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 基于javascript實(shí)現(xiàn)根據(jù)身份證號(hào)碼識(shí)別性別和年齡

    基于javascript實(shí)現(xiàn)根據(jù)身份證號(hào)碼識(shí)別性別和年齡

    這篇文章主要介紹了基于javascript實(shí)現(xiàn)根據(jù)身份證號(hào)碼識(shí)別性別和年齡的相關(guān)資料,需要的朋友可以參考下
    2016-01-01
  • 取得一定長(zhǎng)度的內(nèi)容,處理中文

    取得一定長(zhǎng)度的內(nèi)容,處理中文

    取得一定長(zhǎng)度的內(nèi)容,處理中文...
    2006-12-12
  • 最新評(píng)論

    封丘县| 蓬安县| 靖远县| 明溪县| 苗栗县| 霸州市| 清流县| 金山区| 凤凰县| 乐至县| 九寨沟县| 包头市| 南通市| 海伦市| 三都| 武清区| 莎车县| 沾益县| 连平县| 阳新县| 柘城县| 金门县| 霍林郭勒市| 安顺市| 五华县| 福安市| 文昌市| 山东省| 庆元县| 乌拉特中旗| 苏尼特左旗| 浦城县| 剑阁县| 海城市| 桐梓县| 北京市| 饶平县| 永城市| 若羌县| 朝阳区| 铁力市|