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 相关文章推荐
jscript之Open an Excel Spreadsheet
Jun 13 Javascript
js中通过split函数分割字符串成数组小例子
Sep 21 Javascript
在jquery中combobox多选的不兼容问题总结
Dec 24 Javascript
jQuery截取指定长度字符串代码
Aug 21 Javascript
jQuery响应鼠标事件并隐藏与显示input默认值
Aug 24 Javascript
jQueryMobile之Helloworld与页面切换的方法
Feb 04 Javascript
动态加载js的方法汇总
Feb 13 Javascript
jQuery实现首页顶部可伸缩广告特效代码
Apr 15 Javascript
详解node单线程实现高并发原理与node异步I/O
Sep 21 Javascript
es6中的解构赋值、扩展运算符和rest参数使用详解
Sep 28 Javascript
Angular4学习之Angular CLI的安装与使用教程
Jan 04 Javascript
vue19 组建 Vue.extend component、组件模版、动态组件 的实例代码
Apr 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个人网站架设连环讲(三)
2006/10/09 PHP
PHP隐形一句话后门,和ThinkPHP框架加密码程序(base64_decode)
2011/11/02 PHP
PHP单例模式模拟Java Bean实现方法示例
2018/12/07 PHP
php设计模式之策略模式应用案例详解
2019/06/17 PHP
Sample script that deletes a SQL Server database
2007/06/16 Javascript
js 判断脚本加载完毕的代码
2011/07/13 Javascript
jquery indexOf使用方法
2013/08/19 Javascript
后台获取ZTREE选中节点的方法
2015/02/12 Javascript
jquery判断当前浏览器的实现代码
2015/11/07 Javascript
详解JavaScript UTC时间转换方法
2016/01/07 Javascript
JavaScript实现简洁的俄罗斯方块完整实例
2016/03/01 Javascript
jquery 动态合并单元格的实现方法
2016/08/26 Javascript
JS 事件绑定、事件监听、事件委托详细介绍
2016/09/28 Javascript
bootstrap动态添加面包屑(breadcrumb)及其响应事件的方法
2017/05/25 Javascript
Angular4学习之Angular CLI的安装与使用教程
2018/01/04 Javascript
详解vue-router导航守卫
2019/01/19 Javascript
vue增加强缓存和版本号的实现方法
2019/05/01 Javascript
JS获取当前时间的年月日时分秒及时间的格式化的方法
2019/12/18 Javascript
如何使用JavaScript检测空闲的浏览器选项卡
2020/05/28 Javascript
python正则表达式之作业计算器
2016/03/18 Python
Python 制作糗事百科爬虫实例
2016/09/22 Python
Django实现自定义404,500页面教程
2017/03/26 Python
Python编程实现双链表,栈,队列及二叉树的方法示例
2017/11/01 Python
django缓存配置的几种方法详解
2018/07/16 Python
Python中pymysql 模块的使用详解
2019/08/12 Python
python 函数嵌套及多函数共同运行知识点讲解
2020/03/03 Python
使用css3制作登录表单的步骤
2014/04/07 HTML / CSS
C语言编程练习
2012/04/02 面试题
金融学专业大学生职业生涯规划
2014/03/07 职场文书
安全生产标语
2014/06/06 职场文书
大型主题婚礼活动策划方案
2014/09/15 职场文书
预备党员转正思想汇报
2014/09/26 职场文书
酒店人事专员岗位职责
2015/04/07 职场文书
2015年小学师德师风建设工作总结
2015/10/23 职场文书
志愿服务心得体会
2016/01/15 职场文书
详解MySQL中的主键与事务
2021/05/27 MySQL