Skip to content

设置静态资源

main.ts 是负责启动 Nest 的 ioc 容器的,调用下 useStaticAssets 来支持静态资源的请求

typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.useStaticAssets(join(__dirname, '..', 'public'), { prefix: '/static' });
  await app.listen(2174);
}
bootstrap();

注意: 要给 create 方法传入 NestExpressApplication 的泛型参数才有 useStaticAssets 这些方法的语法提示

我们指定 prefixstatic,然后在静态文件目录 public 下添加一个 html

html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    Ryuki
  </body>
</html>

重启服务,然后浏览器访问下 http://localhost:2174/static/index.html