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 相关文章推荐
connect中间件session、cookie的使用方法分享
Jun 17 Javascript
JavaScript的原型继承详解
Feb 15 Javascript
jquery中ready()函数执行的时机和window的load事件比较
Jun 22 Javascript
js获取Html元素的实际宽度高度的方法
May 19 Javascript
VUE axios发送跨域请求需要注意的问题
Jul 06 Javascript
js数字滑动时钟的简单实现(示例讲解)
Aug 14 Javascript
JS+HTML+CSS实现轮播效果
Nov 28 Javascript
用node-webkit把web应用打包成桌面应用(windows环境)
Feb 01 Javascript
bootstrap+spring boot实现面包屑导航功能(前端代码)
Oct 09 Javascript
JS+html5实现异步上传图片显示上传文件进度条功能示例
Nov 09 Javascript
angula中使用iframe点击后不执行变更检测的问题
May 10 Javascript
vue实现自定义多选按钮
Jul 16 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函数
2008/10/03 PHP
PHP 编程安全性小结
2010/01/08 PHP
IIS下PHP连接数据库提示mysql undefined function mysql_connect()
2010/06/04 PHP
浅析php数据类型转换
2014/01/09 PHP
php格式化日期实例分析
2014/11/12 PHP
PHP实现图片不变型裁剪及图片按比例裁剪的方法
2016/01/14 PHP
php单链表实现代码分享
2016/07/04 PHP
thinkphp多表查询两表有重复相同字段的完美解决方法
2016/09/22 PHP
PHP实现的二分查找算法实例分析
2017/12/19 PHP
Laravel 连接(Join)示例
2019/10/16 PHP
基于jquery实现的定时显示与隐藏div广告的实现代码
2013/08/22 Javascript
script不刷新页面的联动前后代码
2013/09/18 Javascript
jQuery使用之处理页面元素用法实例
2015/01/19 Javascript
js仿百度切换皮肤功能(html+css)
2016/07/10 Javascript
手机浏览器 后退按钮强制刷新页面方法总结
2016/10/09 Javascript
微信小程序 获取相册照片实例详解
2016/11/16 Javascript
使用JS批量选中功能实现更改数据库中的status状态值(批量展示)
2016/11/22 Javascript
jquery获取input type=text中的值的各种方式(总结)
2016/12/02 Javascript
JS中利用localStorage防止页面动态添加数据刷新后数据丢失
2017/03/10 Javascript
vue2.0 + ele的循环表单及验证字段方法
2018/09/18 Javascript
JS实现盒子拖拽效果
2020/02/06 Javascript
js表达式与运算符简单操作示例
2020/02/15 Javascript
Python Sqlite3以字典形式返回查询结果的实现方法
2016/10/03 Python
分享8点超级有用的Python编程建议(推荐)
2019/10/13 Python
Python实现点云投影到平面显示
2020/01/18 Python
python opencv 实现读取、显示、写入图像的方法
2020/06/08 Python
Selenium webdriver添加cookie实现过程详解
2020/08/12 Python
Python 串口通信的实现
2020/09/29 Python
BabyBjörn婴儿背带法国官网:BabyBjorn法国
2018/06/16 全球购物
什么是重载?CTS、CLS和CLR分别做何解释
2012/05/06 面试题
医药类个人求职的自我评价
2014/02/12 职场文书
工商治理实习生的自我评价分享
2014/02/20 职场文书
门面房租房协议书
2014/12/01 职场文书
2015年乡镇妇联工作总结
2015/05/19 职场文书
授权协议书范本(3篇)
2019/10/15 职场文书
JavaScript 原型与原型链详情
2021/11/02 Javascript