Skip to content
On this page

@nestjs/platform-express

@nestjs/platform-express 是 NestJS 框架中的一个平台适配器,用于将 NestJS 应用与 Express.js 集成。NestJS 是一个基于 TypeScript 的进程框架,支持多种底层 HTTP 服务器库,如 Express 和 Fastify。@nestjs/platform-express 提供了将 NestJS 应用运行在 Express.js 之上的能力,使得开发者能够利用 Express.js 的中间件、路由等功能,同时享受 NestJS 提供的模块化、依赖注入、装饰器等高级特性。

主要功能和组成部分

  1. ExpressAdapter

    • 提供适配器接口,用于将 Express.js 与 NestJS 集成。
    • 可以自定义 Express 实例,并将其传递给 NestJS 应用。
  2. File Upload

    • 提供文件上传支持,通过 @nestjs/platform-express 中的 FileInterceptorFilesInterceptor 等装饰器和 Multer 进行文件上传处理。
  3. 中间件 (Middleware)

    • 可以使用 Express.js 中的中间件功能,通过 NestMiddleware 接口和 MiddlewareConsumer 来配置中间件。
  4. 静态文件服务

    • 提供静态文件服务的功能,允许开发者在 NestJS 应用中直接提供静态资源。

代码示例

以下是一个使用 @nestjs/platform-express 构建和启动 NestJS 应用的示例:

1. 基本应用示例

typescript
import { Module, Controller, Get, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import * as express from 'express';

// 控制器
@Controller()
class AppController {
  @Get()
  getHello(): string {
    return 'Hello World!';
  }
}

// 模块
@Module({
  controllers: [AppController],
})
class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    // 配置中间件
  }
}

// 创建和启动应用
async function bootstrap() {
  const server = express();
  const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
  await app.listen(3000);
  console.log('Application is running on: http://localhost:3000');
}
bootstrap();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

2. 文件上传示例

typescript
import { Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';

@Controller('upload')
class UploadController {
  @Post('single')
  @UseInterceptors(FileInterceptor('file', {
    storage: diskStorage({
      destination: './uploads',
      filename: (req, file, callback) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const ext = extname(file.originalname);
        callback(null, `${file.fieldname}-${uniqueSuffix}${ext}`);
      }
    })
  }))
  uploadFile(@UploadedFile() file) {
    console.log(file);
    return { message: 'File uploaded successfully!', file };
  }
}

@Module({
  controllers: [UploadController],
})
class UploadModule {}

async function bootstrap() {
  const app = await NestFactory.create(UploadModule);
  await app.listen(3000);
  console.log('Application is running on: http://localhost:3000');
}
bootstrap();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

3. 静态文件服务示例

import { Module, Controller, Get, MiddlewareConsumer, NestModule } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { join } from 'path';
import { ExpressAdapter } from '@nestjs/platform-express';
import * as express from 'express';

@Controller()
class AppController {
  @Get()
  getHello(): string {
    return 'Hello World!';
  }
}

@Module({
  controllers: [AppController],
})
class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    // 配置静态文件服务
    const server = consumer.apply().getInstance();
    server.use('/static', express.static(join(__dirname, '..', 'public')));
  }
}

async function bootstrap() {
  const server = express();
  const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
  await app.listen(3000);
  console.log('Application is running on: http://localhost:3000');
}
bootstrap();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

结论

@nestjs/platform-express 提供了将 NestJS 与 Express.js 集成的能力,使得开发者可以利用 Express.js 的强大功能,同时享受 NestJS 带来的模块化、依赖注入和装饰器等高级特性。通过使用 @nestjs/platform-express,开发者可以轻松构建高效、可扩展的 Web 应用程序。

沪ICP备20006251号-1