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 相关文章推荐
firefox下input type=&quot;file&quot;的size是多大
Oct 24 Javascript
javascript中Math.random()使用详解
Apr 15 Javascript
Jquery轮播效果实现过程解析
Mar 30 Javascript
Node.js 文件夹目录结构创建实例代码
Jul 08 Javascript
Vue2.0+ElementUI实现表格翻页的实例
Oct 23 Javascript
jQuery EasyUI 折叠面板accordion的使用实例(分享)
Dec 25 jQuery
Angular使用cli生成自定义文件、组件的方法
Sep 04 Javascript
微信小程序自定义带价格显示日历效果
Dec 29 Javascript
基于vue通用表单解决方案的思考与分析
Mar 16 Javascript
使用Vue-Awesome-Swiper实现旋转叠加轮播效果&amp;平移轮播效果
Aug 16 Javascript
Vue使用NProgress进度条的方法
Sep 21 Javascript
vue中如何添加百度统计代码
Dec 19 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
如何在PHP中使用Oracle数据库(3)
2006/10/09 PHP
PHP脚本数据库功能详解(中)
2006/10/09 PHP
PHP中的extract的作用分析
2008/04/09 PHP
php json_encode()函数返回json数据实例代码
2014/10/10 PHP
php上传文件并存储到mysql数据库的方法
2015/03/16 PHP
Symfony2安装第三方Bundles实例详解
2016/02/04 PHP
获取内联和链接中的样式(js代码)
2013/04/11 Javascript
浅析offsetLeft,Left,clientLeft之间的区别
2013/11/30 Javascript
详解jQuery向动态生成的内容添加事件响应jQuery live()方法
2015/11/02 Javascript
简单实现js选项卡切换效果
2016/02/03 Javascript
Javascript的表单验证-初识正则表达式
2016/03/18 Javascript
js利用正则表达式检验输入内容是否为网址
2016/07/05 Javascript
BootStrap下拉菜单和滚动监听插件实现代码
2016/09/26 Javascript
jquery validation验证表单插件
2017/01/07 Javascript
layui选项卡效果实现代码
2017/05/19 Javascript
react-native DatePicker日期选择组件的实现代码
2017/09/12 Javascript
jquery一键控制checkbox全选、反选或全不选
2017/10/16 jQuery
vue.js中$set与数组更新方法
2018/03/08 Javascript
浅谈layui里的上传控件问题
2019/09/26 Javascript
在node环境下parse Smarty模板的使用示例代码
2019/11/15 Javascript
[42:48]完美世界DOTA2联赛PWL S3 Magma vs INK ICE 第二场 12.11
2020/12/16 DOTA
Python基础中所出现的异常报错总结
2016/11/19 Python
浅谈用Python实现一个大数据搜索引擎
2017/11/28 Python
使用python实现快速搭建简易的FTP服务器
2018/09/12 Python
新手入门Python编程的8个实用建议
2019/07/12 Python
keras使用Sequence类调用大规模数据集进行训练的实现
2020/06/22 Python
捷克玩具商店:Bambule
2019/02/23 全球购物
传媒专业推荐信范文
2013/11/23 职场文书
春节活动策划方案
2014/01/24 职场文书
工人先锋号事迹材料
2014/12/24 职场文书
风雨哈佛路观后感
2015/06/03 职场文书
单位车辆管理制度
2015/08/05 职场文书
解读MySQL的客户端和服务端协议
2021/05/10 MySQL
详解Go与PHP的语法对比
2021/05/29 PHP
Vue过滤器(filter)实现及应用场景详解
2021/06/15 Vue.js
Jpa Specification如何实现and和or同时使用查询
2021/11/23 Java/Android