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代码
Nov 09 Javascript
jquery ui 1.7 ui.tabs 动态添加与关闭(按钮关闭+双击关闭)
Apr 01 Javascript
jquery.simple.tree插件 更简单,兼容性更好的无限树插件
Sep 03 Javascript
自用js开发框架小成 学习js的朋友可以看看
Nov 16 Javascript
js分页工具实例
Jan 28 Javascript
JS实现窗口加载时模拟鼠标移动的方法
Jun 03 Javascript
BootStrap栅格系统、表单样式与按钮样式源码解析
Jan 20 Javascript
Javascript实现找不同色块的游戏
Jul 17 Javascript
vue实现表格增删改查效果的实例代码
Jul 18 Javascript
angular4中关于表单的校验示例
Oct 16 Javascript
vue 使用element-ui中的Notification自定义按钮并实现关闭功能及如何处理多个通知
Aug 17 Javascript
vue3.0 的 Composition API 的使用示例
Oct 26 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
在IIS上安装PHP4.0正式版
2006/10/09 PHP
thinkphp的CURD和查询方式介绍
2013/12/19 PHP
PHP加密解密字符串汇总
2015/04/26 PHP
php使用cookie实现记住登录状态
2015/04/27 PHP
jQuery实现图片放大预览实现原理及代码
2013/09/12 Javascript
jQuery DOM操作实例
2014/03/05 Javascript
node.js中watch机制详解
2014/11/17 Javascript
2014 HTML5/CSS3热门动画特效TOP10
2014/12/07 Javascript
jquery滚动加载数据的方法
2015/03/09 Javascript
jQuery固定元素插件scrolltofixed使用指南
2015/04/21 Javascript
jquery带有索引按钮且自动轮播切换特效代码分享
2015/09/15 Javascript
jquery插件jquery.LightBox.js实现点击放大图片并左右点击切换效果(附demo源码下载)
2016/02/25 Javascript
javascript实现根据汉字获取简拼
2016/09/25 Javascript
jsp 网站引入外部css或者js失效问题解决
2016/10/31 Javascript
微信小程序 图片宽度自适应的实现
2017/04/06 Javascript
深入浅出webpack教程系列_安装与基本打包用法和命令参数详解
2017/09/10 Javascript
socket io与vue-cli的结合使用的示例代码
2018/11/01 Javascript
jQuery点击页面其他部分隐藏下拉菜单功能
2018/11/27 jQuery
我所理解的JavaScript中的this指向
2020/09/04 Javascript
[01:31]DOTA2上海特级锦标赛 SECRET战队完整宣传片
2016/03/16 DOTA
python 实现网上商城,转账,存取款等功能的信用卡系统
2016/07/15 Python
Python开发虚拟环境使用virtualenvwrapper的搭建步骤教程图解
2018/09/19 Python
Python lambda表达式filter、map、reduce函数用法解析
2019/09/11 Python
使用Python给头像戴上圣诞帽的图像操作过程解析
2019/09/20 Python
医学院护理专业应届生求职信
2013/11/12 职场文书
上班睡觉检讨书
2014/01/09 职场文书
大学生创业感言
2014/01/25 职场文书
副董事长岗位职责
2014/04/02 职场文书
合作经营协议书
2014/04/17 职场文书
班训口号大全
2014/06/18 职场文书
实习班主任自我评价
2015/03/11 职场文书
《我是什么》教学反思
2016/02/16 职场文书
创业计划书之情侣餐厅
2019/09/29 职场文书
node快速搭建后台的实现步骤
2022/02/18 NodeJs
MySQL查询日期时间
2022/05/15 MySQL
SQL Server使用CROSS APPLY与OUTER APPLY实现连接查询
2022/05/25 SQL Server