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 相关文章推荐
求得div 下 img的src地址的js代码
Feb 28 Javascript
Javascript图像处理思路及实现代码
Dec 25 Javascript
extjs两个tbar问题探讨
Aug 08 Javascript
JS中事件冒泡和事件捕获介绍
Dec 13 Javascript
用move.js库实现百叶窗特效
Feb 08 Javascript
js清除浏览器缓存的几种方法
Mar 15 Javascript
JS实现的哈夫曼编码示例【原始版与修改版】
Apr 22 Javascript
Vue封装的可编辑表格插件方法
Aug 28 Javascript
vue悬浮可拖拽悬浮按钮的实例代码
Aug 20 Javascript
jQuery利用cookie 实现本地收藏功能(不重复无需多次命名)
Nov 07 jQuery
vue-router 控制路由权限的实现
Sep 24 Javascript
vue实现下拉菜单树
Oct 22 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 download.php实现代码 跳转到下载文件(response.redirect)
2009/08/26 PHP
php发送短信验证码完成注册功能
2015/11/24 PHP
[原创]php集成安装包wampserver修改密码后phpmyadmin无法登陆的解决方法
2016/11/23 PHP
PHP获取远程http或ftp文件的md5值的方法
2019/04/15 PHP
javascript encodeURI和encodeURIComponent的比较
2010/04/03 Javascript
学习面向对象之面向对象的基本概念:对象和其他基本要素
2010/11/30 Javascript
输入自动提示搜索提示功能的javascript:sugggestion.js
2013/09/02 Javascript
JavaScript代码编写中各种各样的坑和填坑方法
2014/06/06 Javascript
javascript实现锁定网页、密码解锁效果(类似系统屏幕保护效果)
2014/08/15 Javascript
jQuery删除节点用法示例(remove方法)
2016/09/08 Javascript
AngularJS equal比较对象实例详解
2016/09/14 Javascript
使用BootStrap实现悬浮窗口的效果
2016/12/13 Javascript
Angular2学习教程之TemplateRef和ViewContainerRef详解
2017/05/25 Javascript
Vue的Flux框架之Vuex状态管理器
2017/07/30 Javascript
element-ui 中的table的列隐藏问题解决
2018/08/24 Javascript
js 使用ajax设置和获取自定义header信息的方法小结
2020/03/12 Javascript
python编写暴力破解FTP密码小工具
2014/11/19 Python
Python编程实现及时获取新邮件的方法示例
2017/08/10 Python
用python实现的线程池实例代码
2018/01/06 Python
Python3读取Excel数据存入MySQL的方法
2018/05/04 Python
Python实现的txt文件去重功能示例
2018/07/07 Python
python虚拟环境完美部署教程
2019/08/06 Python
python PIL/cv2/base64相互转换实例
2020/01/09 Python
Python如何定义有默认参数的函数
2020/08/10 Python
html5实现九宫格抽奖可固定抽中某项奖品
2020/06/15 HTML / CSS
德国自行车商店:Tretwerk
2019/06/21 全球购物
Feelunique中文官网:欧洲最大化妆品零售电商
2020/07/10 全球购物
下列程序在32位linux或unix中的结果是什么
2014/03/25 面试题
生物学学生自我评价
2014/01/17 职场文书
《小熊住山洞》教学反思
2014/02/21 职场文书
我爱祖国演讲稿
2014/09/02 职场文书
护士长2014年度工作总结
2014/11/11 职场文书
三峡人家导游词
2015/01/31 职场文书
2015年新农村建设指导员工作总结
2015/07/24 职场文书
餐饮行业关注的9大营销策略
2019/08/26 职场文书
Python-OpenCV教程之图像的位运算详解
2021/06/21 Python