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 DOM学习第一章 W3C DOM简介
Feb 19 Javascript
JavaScript中对循环语句的优化技巧深入探讨
Jun 06 Javascript
jquery.uploadify插件在chrome浏览器频繁崩溃解决方法
Mar 01 Javascript
深入探秘jquery瀑布流的实现
Jan 30 Javascript
JS简单实现DIV相对于浏览器固定位置不变的方法
Jun 17 Javascript
微信小程序 弹幕功能简单实例
Feb 14 Javascript
前端构建工具之gulp的语法教程
Jun 12 Javascript
打造通用的匀速运动框架(实例讲解)
Oct 17 Javascript
微信小程序scroll-view仿拼多多横向滑动滚动条
Apr 21 Javascript
详解ES6 Fetch API HTTP请求实用指南
Nov 14 Javascript
JavaScript中0、空字符串、'0'是true还是false的知识点分享
Sep 16 Javascript
Vue.js中的高级面试题及答案
Jan 13 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中创建空文件的代码[file_put_contents vs touch]
2012/01/20 PHP
PHP判断指定时间段的2个方法
2014/03/14 PHP
php绘图之在图片上写中文和英文的方法
2015/01/24 PHP
PHP如何实现Unicode和Utf-8编码相互转换
2015/07/29 PHP
使用prototype.js进行异步操作
2007/02/07 Javascript
自己编写的类似JS的trim方法
2013/10/09 Javascript
JS复制内容到剪切板的实例代码(兼容IE与火狐)
2013/11/19 Javascript
jQuery垂直多级导航菜单代码分享
2015/08/18 Javascript
jQuery实现两个select控件的互移操作
2016/12/22 Javascript
AngularJS 最常用的八种功能(基础知识)
2017/06/26 Javascript
在Vue中用canvas实现二维码和图片合成海报的方法
2019/06/10 Javascript
浅谈vue项目用到的mock数据接口的两种方式
2019/10/09 Javascript
uni-app从安装到卸载的入门教程
2020/05/15 Javascript
python正则表达式修复网站文章字体不统一的解决方法
2013/02/21 Python
Python使用正则表达式分割字符串的实现方法
2019/07/16 Python
python傅里叶变换FFT绘制频谱图
2019/07/19 Python
python代码 FTP备份交换机配置脚本实例解析
2019/08/01 Python
jupyter notebook插入本地图片的实现
2020/04/13 Python
Python-jenkins 获取job构建信息方式
2020/05/12 Python
Keras SGD 随机梯度下降优化器参数设置方式
2020/06/19 Python
13个Pandas实用技巧,助你提高开发效率
2020/08/19 Python
Numpy(Pandas)删除全为零的列的方法
2020/09/11 Python
详解Python中第三方库Faker
2020/09/25 Python
科茨沃尔德家居商店:Scotts of Stow
2018/06/29 全球购物
捷克浴室和厨房设备购物网站:SIKO
2018/08/11 全球购物
请问软件开发中的设计模式你会使用哪些
2015/05/13 面试题
电厂厂长岗位职责
2014/01/02 职场文书
幼儿园秋游感想
2014/03/12 职场文书
绿色环保演讲稿
2014/05/10 职场文书
优秀实习生主要事迹
2014/05/29 职场文书
中药学专业求职信
2014/05/31 职场文书
老乡聚会通知
2015/04/23 职场文书
2015年文明创建工作总结
2015/04/30 职场文书
工作迟到检讨书范文
2015/05/06 职场文书
MSSQL基本语法操作
2022/04/11 SQL Server
MySql分区类型及创建分区的方法
2022/04/13 MySQL