Skip to content

Nest 实战 (六)

设置静态资源两种方法

设置静态文件访问路径(1)

(1) 创建目录

根目录下创建 upload 文件夹,放入一张图片1.jpg

(2) 设置

  • (一) main.js 里面设置好静态路径
js
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import rateLimit from "express-rate-limit";
// 配置文件
import { ConfigService } from "@nestjs/config";
// 静态
import { join } from "path";
import { NestExpressApplication } from "@nestjs/platform-express";
async function bootstrap() {
  const app =
    (await NestFactory.create) <
    NestExpressApplication >
    (AppModule,
    {
      cors: true, // 开启跨域访问
    });

  // 限制请求频率
  app.use(
    rateLimit({
      windowMs: 15 * 60 * 1000, // 15分钟
      max: 1000, // 限制15分钟内最多只能访问1000次
    })
  );

  // 获取配置文件
  const config = app.get(ConfigService);

  // 设置 api 访问前缀
  const prefix = config.get < string > "app.prefix" || "";
  app.setGlobalPrefix(prefix);

  // 设置静态资源路径
  const rootPath = process.cwd();
  const baseDirPath = join(rootPath, config.get("app.file.location") || "");

  app.useStaticAssets(baseDirPath, {
    prefix: "/profile/", // 虚拟路径
    maxAge: 86400000 * 365, // 过期时间 我设置成1年
  });

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
  • (二) 设置配置文件
bash
# 开发环境配置
app:
  prefix: 'v1'
  port: 8080
  logger:
    # 项目日志存储路径,相对路径(相对本项目根目录)或绝对路径
    dir: '../logs'
  # 文件相关
  file:
    # 是否为本地文件服务或cos
    isLocal: true
    # location 文件上传后存储目录,相对路径(相对本项目根目录)或绝对路径
    # 名字你自己随意起 但是要创建文件夹得目录对上
    location: 'upload'
    # 文件服务器地址,这是开发环境的配置 生产环境请自行配置成可访问域名
    domain: 'http://localhost:8080'
    # 文件虚拟路径, 必须以 / 开头, 如 http://localhost:8080/profile/****.jpg  , 如果不需要则 设置 ''
    serveRoot: '/profile'
    # 文件大小限制,单位M
    maxSize: 10

(3) 调用

bash
http://localhost:3000/profile/1.jpg

设置静态文件访问路径(2)

nest static module

安装

bash
pnpm install --save @nestjs/serve-static

AppModule

ts
import { Module, Global } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import configuration from "./config/index";
// 静态文件模块
import { ServeStaticModule } from "@nestjs/serve-static";
import { join } from "path";
@Global()
@Module({
  imports: [
    // 配置模块
    ConfigModule.forRoot({
      cache: true,
      load: [configuration],
      isGlobal: true,
    }),
    // 静态模块
    ServeStaticModule.forRoot({
      // 根目录
      rootPath: join(__dirname, "..", "public"),
      // 虚拟根路径
      serveRoot: "/static",
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

根目录新建 public 文件夹

里面随便放一张照片 然后访问即可

bash
http://localhost:8080/static/1.jpg