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购物车实时结算特效实现思路
Sep 23 Javascript
深入理解JavaScript系列(43):设计模式之状态模式详解
Mar 04 Javascript
AngularJS指令详解及示例代码
Aug 16 Javascript
微信小程序 参数传递详解
Oct 24 Javascript
react-native 完整实现登录功能的示例代码
Sep 11 Javascript
JS控制鼠标拒绝点击某一按钮的实例
Dec 29 Javascript
vue中简单弹框dialog的实现方法
Feb 26 Javascript
详解vue 数据传递的方法
Apr 19 Javascript
vue ssr 实现方式(学习笔记)
Jan 18 Javascript
vue的路由映射问题及解决方案
Oct 14 Javascript
vue中el-input绑定键盘按键(按键修饰符)
Jul 22 Javascript
我所理解的JavaScript中的this指向
Sep 04 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 is_file()和is_dir()用于遍历目录时用法注意事项
2010/03/02 PHP
领悟php接口中interface存在的意义
2013/06/27 PHP
php调用google接口生成二维码示例
2014/04/28 PHP
教你识别简单的免查杀PHP后门
2015/09/13 PHP
thinkphp 框架数据库切换实现方法分析
2020/05/18 PHP
js字符编码函数区别分析
2008/06/05 Javascript
jquery中this的使用说明
2010/09/06 Javascript
JS和jquery获取各种屏幕的宽度和高度的代码
2013/08/02 Javascript
jquery监听div内容的变化具体实现思路
2013/11/04 Javascript
Jquery 切换不同图片示例代码
2013/12/05 Javascript
JQuery解析HTML、JSON和XML实例详解
2014/03/29 Javascript
jQuery回调函数的定义及用法实例
2014/12/23 Javascript
javascript实现简单的分页特效
2015/08/12 Javascript
js实现仿Discuz文本框弹出层效果
2015/08/13 Javascript
JavaScript是如何实现继承的(六种方式)
2016/03/31 Javascript
JS实现动态增加和删除li标签行的实例代码
2016/10/16 Javascript
详解Node.js 命令行程序开发教程
2017/06/07 Javascript
JavaScript之filter_动力节点Java学院整理
2017/06/28 Javascript
js计算最大公约数和最小公倍数代码实例
2019/09/11 Javascript
vue实现图片懒加载的方法分析
2020/02/05 Javascript
微信小程序用户盒子、宫格列表的实现
2020/07/01 Javascript
Python模糊查询本地文件夹去除文件后缀的实例(7行代码)
2017/11/09 Python
python+selenium实现自动抢票功能实例代码
2018/11/23 Python
python实现提取str字符串/json中多级目录下的某个值
2020/02/27 Python
Python JSON常用编解码方法代码实例
2020/09/05 Python
Python requests接口测试实现代码
2020/09/08 Python
canvas粒子动画背景的实现示例
2018/09/03 HTML / CSS
美国最值得信赖的宠物药房:Allivet
2019/03/23 全球购物
AVI-8手表美国官方商店:AVI-8 USA
2019/04/10 全球购物
全球最受追捧的运动服品牌领先数字目的地:Stylerunner
2020/11/25 全球购物
工作室成员个人发展规划范文
2014/01/24 职场文书
建设投标担保书
2014/05/13 职场文书
相亲大会策划方案
2014/06/05 职场文书
亚布力滑雪场导游词
2015/02/09 职场文书
2016年中秋节慰问信
2015/12/01 职场文书
个人工作失误的保证书怎么写?
2019/06/21 职场文书