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 相关文章推荐
js 事件处理函数间的Event物件是否全等
Apr 08 Javascript
javascript之querySelector和querySelectorAll使用介绍
Dec 20 Javascript
深入理解JavaScript系列(30):设计模式之外观模式详解
Mar 03 Javascript
jQuery中大家不太了解的几个方法
Mar 04 Javascript
javascript实现一个简单的弹出窗
Feb 22 Javascript
JavaScript简单实现弹出拖拽窗口(一)
Jun 17 Javascript
通过jquery.cookie.js实现记住用户名、密码登录功能
Jun 20 jQuery
微信小程序 生成携带参数的二维码
Oct 23 Javascript
详解node和ES6的模块导出与导入
Feb 19 Javascript
vue项目,代码提交至码云,iconfont的用法说明
Jul 30 Javascript
关于IDEA中的.VUE文件报错 Export declarations are not supported by current JavaScript version
Oct 17 Javascript
vue 组件基础知识总结
Jan 26 Vue.js
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
Syphon 虹吸式咖啡壶冲煮–拨动法
2021/03/03 冲泡冲煮
php中判断文件存在是用file_exists还是is_file的整理
2012/09/12 PHP
解析php中call_user_func_array的作用
2013/06/07 PHP
CURL状态码列表(详细)
2013/06/27 PHP
php实现比较两个字符串日期大小的方法
2015/05/12 PHP
PHP编写RESTful接口
2016/02/23 PHP
配置Nginx+PHP的正确思路与过程
2016/05/10 PHP
Jquery 表格合并的问题分享
2011/09/17 Javascript
关于javascript function对象那些迷惑分析
2011/10/24 Javascript
30个让人兴奋的视差滚动(Parallax Scrolling)效果网站
2012/03/04 Javascript
一个JS的日期格式化算法示例
2013/07/31 Javascript
ExtJS DOM元素操作经验分享
2013/08/28 Javascript
在jquery中combobox多选的不兼容问题总结
2013/12/24 Javascript
JS取request值以及自动执行使用示例
2014/02/24 Javascript
js判断横竖屏及禁止浏览器滑动条示例
2014/04/29 Javascript
JavaScript使表单中的内容显示在屏幕上的方法
2015/06/29 Javascript
javascript中使用未定义变量或值的情况分析
2016/07/19 Javascript
微信小程序 教程之WXSS
2016/10/18 Javascript
js实现日历的简单算法
2017/01/24 Javascript
解析Vue2 dist 目录下各个文件的区别
2017/11/22 Javascript
jquery实现动态创建form并提交的方法示例
2019/05/27 jQuery
Python删除windows垃圾文件的方法
2015/07/14 Python
Python之list对应元素求和的方法
2018/06/28 Python
python opencv鼠标事件实现画框圈定目标获取坐标信息
2020/04/18 Python
vscode 配置 python3开发环境的方法
2019/09/19 Python
python将字母转化为数字实例方法
2019/10/04 Python
Python和Sublime整合过程图示
2019/12/25 Python
python 常见的排序算法实现汇总
2020/08/21 Python
初探CSS3中的calc()功能
2015/07/14 HTML / CSS
英国时尚服饰电商:Boohoo
2017/10/12 全球购物
英国50岁以上人群的交友网站:Ourtime
2018/03/28 全球购物
Bath & Body Works阿联酋:在线购买沐浴和身体用品
2021/02/27 全球购物
Java编程面试题
2016/04/04 面试题
爷爷追悼会答谢词
2014/01/24 职场文书
集体婚礼策划方案
2014/02/22 职场文书
SpringBoot SpringEL表达式的使用
2021/07/25 Java/Android