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 相关文章推荐
十个优秀的Ajax/Javascript实例网站收集
Mar 31 Javascript
JQury slideToggle闪烁问题及解决办法
Jul 05 Javascript
js Event对象的5种坐标
Sep 12 Javascript
jQuery 遍历-nextUntil()方法以及prevUntil()方法的使用介绍
Apr 26 Javascript
JavaScript检测鼠标移动方向的方法
May 22 Javascript
JavaScript实现的圆形浮动标签云效果实例
Aug 06 Javascript
js控住DOM实现发布微博效果
Aug 30 Javascript
JS判断非空至少输入两个字符的简单实现方法
Jun 23 Javascript
Vue-cli配置打包文件本地使用的教程图解
Aug 02 Javascript
详解如何在webpack中做预渲染降低首屏空白时间
Aug 22 Javascript
vue计算属性get和set用法示例
Feb 08 Javascript
javascript中导出与导入实现模块化管理教程
Dec 03 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语法(2)
2006/10/09 PHP
php adodb操作mysql数据库
2009/03/19 PHP
php使用pdo连接sqlite3的配置示例
2016/05/27 PHP
php实现生成PDF文件的方法示例【基于FPDF类库】
2018/07/21 PHP
IE8 下的Js错误HTML Parsing Error...
2009/08/14 Javascript
jQuery的12招常用技巧分享
2011/08/08 Javascript
JavaScript执行顺序详细介绍
2013/12/04 Javascript
JQuery EasyUI 加载两次url的原因分析及解决方案
2014/08/18 Javascript
AngularJS语法详解
2015/01/23 Javascript
jQuery检测返回值的数据类型
2015/07/13 Javascript
基于JavaScript实现动态添加删除表格的行
2016/02/01 Javascript
浅析AMD CMD CommonJS规范--javascript模块化加载学习心得总结
2016/03/16 Javascript
Jquery组件easyUi实现选项卡切换示例
2016/08/23 Javascript
Vue.js每天必学之计算属性computed与$watch
2016/09/05 Javascript
connection reset by peer问题总结及解决方案
2016/10/21 Javascript
详解Vue中使用v-for语句抛出错误的解决方案
2017/05/04 Javascript
vue.js组件vue-waterfall-easy实现瀑布流效果
2017/08/22 Javascript
js 毫秒转天时分秒的实例
2017/11/17 Javascript
Vue对象赋值视图不更新问题及解决方法
2019/06/03 Javascript
你了解vue3.0响应式数据怎么实现吗
2019/06/07 Javascript
JavaScript使用canvas绘制随机验证码
2020/02/17 Javascript
详解element-ui动态限定的日期范围选择器代码片段
2020/07/03 Javascript
Python输出PowerPoint(ppt)文件中全部文字信息的方法
2015/04/28 Python
python使用reportlab实现图片转换成pdf的方法
2015/05/22 Python
Python操作RabbitMQ服务器实现消息队列的路由功能
2016/06/29 Python
使用python调用zxing库生成二维码图片详解
2017/01/10 Python
Python遍历某目录下的所有文件夹与文件路径
2018/03/15 Python
pytorch 中pad函数toch.nn.functional.pad()的用法
2020/01/08 Python
在Anaconda3下使用清华镜像源安装TensorFlow(CPU版)
2020/04/19 Python
HTML5自定义视频播放器源码
2020/01/06 HTML / CSS
草莓网化妆品日本站:Strawberrynet日本
2017/10/20 全球购物
出门问问全球官方商城:Tichome音箱和TicWatch智能手表
2017/12/02 全球购物
娇韵诗香港官网:Clarins香港
2020/08/13 全球购物
外贸采购员岗位职责
2014/03/08 职场文书
质量管理标语
2014/06/12 职场文书
代码解析React中setState同步和异步问题
2021/06/03 Javascript