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 相关文章推荐
用Javascript读取中文COOKIE的解决办法
Feb 15 Javascript
点击下载链接 弹出页面实现代码
Oct 01 Javascript
javascript 循环读取JSON数据的代码
Jul 17 Javascript
JS常见问题整理(持续更新)
Aug 06 Javascript
Bootstrap Navbar Component实现响应式导航
Oct 08 Javascript
详解JavaScript 中getElementsByName在IE中的注意事项
Feb 21 Javascript
js实现3D图片环展示效果
Mar 09 Javascript
Bootstrap Table 删除和批量删除
Sep 22 Javascript
解决vue中虚拟dom,无法实时更新的问题
Sep 15 Javascript
基于vue实现一个禅道主页拖拽效果
May 27 Javascript
深入浅析golang zap 日志库使用(含文件切割、分级别存储和全局使用等)
Feb 19 Javascript
vue单应用在ios系统中实现微信分享功能操作
Sep 07 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
记录mysql性能查询过程的使用方法
2013/05/02 PHP
Zend Framework前端控制器用法示例
2016/12/11 PHP
php数据序列化测试实例详解
2017/08/12 PHP
PHP实现数组转JSon和JSon转数组的方法示例
2018/06/14 PHP
laravel Model 执行事务的实现
2019/10/10 PHP
ThinkPHP5 框架引入 Go AOP,PHP AOP编程项目详解
2020/05/12 PHP
BOOM vs RR BO5 第三场 2.14
2021/03/10 DOTA
用JS操作FRAME中的IFRAME及其内容的实现代码
2008/07/26 Javascript
原生js编写设为首页兼容ie、火狐和谷歌
2014/06/05 Javascript
javascript获取当前鼠标坐标的方法
2015/01/10 Javascript
jQuery中的pushStack实现原理和应用实例
2015/02/03 Javascript
javascript动态创建表格及添加数据实例详解
2015/05/13 Javascript
在JavaScript中用getMinutes()方法返回指定的分时刻
2015/06/10 Javascript
微信小程序 http请求详细介绍
2016/10/09 Javascript
Vue实现一个返回顶部backToTop组件
2017/07/25 Javascript
微信小程序 功能函数小结(手机号验证*、密码验证*、获取验证码*)
2017/12/08 Javascript
vue.js实现的绑定class操作示例
2018/07/06 Javascript
浅谈webpack4.x 入门(一篇足矣)
2018/09/05 Javascript
Vue项目报错:Uncaught SyntaxError: Unexpected token
2018/11/10 Javascript
Layui带搜索的下拉框的使用以及动态数据绑定方法
2019/09/28 Javascript
vue中动态select的使用方法示例
2019/10/28 Javascript
Python面向对象编程基础解析(二)
2017/10/26 Python
使用Python通过win32 COM实现Word文档的写入与保存方法
2018/05/08 Python
python操作文件的参数整理
2019/06/11 Python
TensorFlow实现checkpoint文件转换为pb文件
2020/02/10 Python
python如何把字符串类型list转换成list
2020/02/18 Python
python微信公众号开发简单流程实现
2020/03/09 Python
Python的logging模块基本用法
2020/12/24 Python
俄罗斯电子产品、计算机和家用电器购物网站:OLDI
2019/10/27 全球购物
俄罗斯天然和有机产品、健康生活网上商店:Fitomarket.ru
2020/10/09 全球购物
医药营销个人求职信范文
2014/02/07 职场文书
节水倡议书范文
2014/04/15 职场文书
无传销社区工作方案
2014/05/13 职场文书
公务员年度考核登记表个人总结
2015/02/12 职场文书
初婚初育证明范本
2015/06/18 职场文书
中职班主任培训心得体会
2016/01/07 职场文书