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中Eval函数的使用说明
Oct 11 Javascript
jQuery下通过replace字符串替换实现大小图片切换
May 22 Javascript
jQuery中[attribute^=value]选择器用法实例
Dec 31 Javascript
js实现常用排序算法
Aug 09 Javascript
zTree jQuery 树插件的使用(实例讲解)
Sep 25 jQuery
微信小程序实现流程进度的图样式功能
Jan 16 Javascript
基于vue打包后字体和图片资源失效问题的解决方法
Mar 06 Javascript
深入理解JavaScript和TypeScript中的class
Apr 22 Javascript
在Vue组件中获取全局的点击事件方法
Sep 06 Javascript
微信小程序页面上下滚动效果
Nov 18 Javascript
jstree中的checkbox默认选中和隐藏示例代码
Dec 29 Javascript
vue项目中在可编辑div光标位置插入内容的实现代码
Jan 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
php+oracle 分页类
2006/10/09 PHP
不用数据库的多用户文件自由上传投票系统(3)
2006/10/09 PHP
ThinkPHP的RBAC(基于角色权限控制)深入解析
2013/06/17 PHP
CodeIgniter针对数据库的连接、配置及使用方法
2016/03/03 PHP
Open and Print a Word Document
2007/06/15 Javascript
JQuery最佳实践之精妙的自定义事件
2010/08/11 Javascript
js变换显示图片的实例
2013/04/16 Javascript
jquery在项目中做复选框时遇到的一些问题笔记
2013/11/17 Javascript
jquery实现input输入框实时输入触发事件代码
2014/01/28 Javascript
js取模(求余数)隔行变色
2014/05/15 Javascript
很棒的js Tab选项卡切换效果
2016/08/30 Javascript
vue中用H5实现文件上传的方法实例代码
2017/05/27 Javascript
vue2.0 子组件改变props值,并向父组件传值的方法
2018/03/01 Javascript
vue表单中遍历表单操作按钮的显示隐藏示例
2019/10/30 Javascript
ES6箭头函数和扩展实例分析
2020/05/23 Javascript
[59:26]DOTA2上海特级锦标赛D组资格赛#1 EG VS VP第二局
2016/02/28 DOTA
[01:38]【DOTA2亚洲邀请赛】Sumail——梦开始的地方
2017/03/03 DOTA
[01:38]完美世界高校联赛决赛花絮
2018/12/02 DOTA
[54:17]DOTA2-DPC中国联赛定级赛 RNG vs iG BO3第二场 1月10日
2021/03/11 DOTA
Python基于list的append和pop方法实现堆栈与队列功能示例
2017/07/24 Python
Python使用requests及BeautifulSoup构建爬虫实例代码
2018/01/24 Python
Python3实现将本地JSON大数据文件写入MySQL数据库的方法
2018/06/13 Python
Django中celery执行任务结果的保存方法
2019/07/12 Python
pytorch 获取层权重,对特定层注入hook, 提取中间层输出的方法
2019/08/17 Python
keras中的loss、optimizer、metrics用法
2020/06/15 Python
Waterford英国官方网站:世界上最受欢迎的优质水晶品牌
2019/08/17 全球购物
会计学财务管理专业个人的自我评价
2013/10/19 职场文书
医学类个人求职信范文
2014/02/05 职场文书
大学生演讲稿
2014/04/25 职场文书
和睦家庭事迹
2014/05/14 职场文书
本科生求职信
2014/06/17 职场文书
2014年招生工作总结
2014/11/26 职场文书
申请吧主发表的感言
2015/08/03 职场文书
2016年教师节特级教师获奖感言
2015/12/09 职场文书
幽默口才训练经典句子(48句)
2019/08/19 职场文书
Redis监控工具RedisInsight安装与使用
2022/03/21 Redis