欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

NestJs 静态目录配置详解

程序员文章站 2023-02-16 10:33:51
网上查看了很多文档,发现很多都是自己实现中间件来完成此功能,不仅浪费时间,而且增加了太多的代码量。实际上,nest已经帮助我们封装好了相关功能。 1、查找线索 由于官方...

网上查看了很多文档,发现很多都是自己实现中间件来完成此功能,不仅浪费时间,而且增加了太多的代码量。实际上,nest已经帮助我们封装好了相关功能。

1、查找线索

由于官方文档没有做详细解释说明,那么我们可以从此框架底层入手:

我们知道,nestjs底层用的是express,那么express是通过什么来完成静态目录构建的:

serve-static

2、搜索源码

我们在项目搜索栏目中搜索“serve-static”会发现如下图:

NestJs 静态目录配置详解

也就是说,当我们在使用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目录:

NestJs 静态目录配置详解

目录创建.png

4、测试效果:

首先使用nestjs自带的upload api来上传文件,这里不做过多说明,最终通过postman完成测试文件上传:

NestJs 静态目录配置详解

测试上传.png

再使用浏览器浏览:

NestJs 静态目录配置详解

浏览图片.gif

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。