NestJs 静态目录配置详解


Posted in Javascript onMarch 12, 2019

网上查看了很多文档,发现很多都是自己实现中间件来完成此功能,不仅浪费时间,而且增加了太多的代码量。实际上,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

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

Javascript 相关文章推荐
jQuery层动画定位滑动效果的方法
Apr 30 Javascript
jquery超简单实现手风琴效果的方法
Jun 05 Javascript
简介JavaScript中setUTCSeconds()方法的使用
Jun 12 Javascript
JavaScript中的call方法和apply方法使用对比
Aug 12 Javascript
深入浅析react native es6语法
Dec 09 Javascript
AngularJS中$http的交互问题
Mar 29 Javascript
JavaScript for循环 if判断语句(学习笔记)
Oct 11 Javascript
微信小程序实现带参数的分享功能(两种方法)
May 17 Javascript
浅谈Vue2.4.0 $attrs与inheritAttrs的具体使用
Mar 08 Javascript
JavaScript动画实例之粒子文本的实现方法详解
Jul 28 Javascript
解决vue-router 嵌套路由没反应的问题
Sep 22 Javascript
JavaScript读取本地文件常用方法流程解析
Oct 12 Javascript
JavaScript使用小插件实现倒计时的方法讲解
Mar 11 #Javascript
30分钟精通React今年最劲爆的新特性——React Hooks
Mar 11 #Javascript
记录一次完整的react hooks实践
Mar 11 #Javascript
es6数值的扩展方法
Mar 11 #Javascript
Vue实现一个图片懒加载插件
Mar 11 #Javascript
使用Jenkins部署React项目的方法步骤
Mar 11 #Javascript
vue基础之v-bind属性、class和style用法分析
Mar 11 #Javascript
You might like
php解压文件代码实现php在线解压
2014/02/13 PHP
php实现在多维数组中查找特定value的方法
2015/07/29 PHP
PHP实现的分解质因数操作示例
2018/08/01 PHP
javascript实现上传图片并预览的效果实现代码
2011/04/11 Javascript
jQuery-Easyui 1.2 实现多层菜单效果的代码
2012/01/13 Javascript
JavaScript的setAttribute兼容性问题解决方法
2013/11/11 Javascript
jquery简单实现滚动条下拉DIV固定在头部不动
2013/11/25 Javascript
jquery实现邮箱自动补全功能示例分享
2014/02/17 Javascript
jQuery实现选项卡切换效果简单演示
2015/12/09 Javascript
最简单的JavaScript图片轮播代码(两种方法)
2015/12/18 Javascript
轻松掌握jQuery中wrap()与unwrap()函数的用法
2016/05/24 Javascript
javascript动画之模拟拖拽效果篇
2016/09/26 Javascript
vue.js表格分页示例
2016/10/18 Javascript
Three.js利用顶点绘制立方体的方法详解
2017/09/27 Javascript
jquery中attr、prop、data区别与用法分析
2019/09/25 jQuery
node+multer实现图片上传的示例代码
2020/02/18 Javascript
Python循环语句之break与continue的用法
2015/10/14 Python
解决Tensorflow使用pip安装后没有model目录的问题
2018/06/13 Python
django中使用Celery 布式任务队列过程详解
2019/07/29 Python
详解Python3定时器任务代码
2019/09/23 Python
python的faker库用法
2019/11/28 Python
TensorFlow使用Graph的基本操作的实现
2020/04/22 Python
浅谈Python 参数与变量
2020/06/20 Python
python dir函数快速掌握用法技巧
2020/12/09 Python
Pycharm制作搞怪弹窗的实现代码
2021/02/19 Python
CSS3 旋转立方体问题详解
2020/01/09 HTML / CSS
日本最新流行服饰网购:Nissen
2016/07/24 全球购物
英国演唱会订票网站:Ticket Selection
2018/03/27 全球购物
三星新西兰官网:Samsung新西兰
2019/03/05 全球购物
委托与事件是什么关系?为什么要使用委托
2014/04/18 面试题
外语系毕业生自荐信范文
2013/12/16 职场文书
2014自荐信的写作技巧
2014/01/28 职场文书
行政文秘岗位职责范本
2014/02/10 职场文书
老师对学生的评语
2014/04/18 职场文书
大学生自荐信怎么写
2015/03/26 职场文书
青年志愿者活动感想
2015/08/07 职场文书