模型-视图-控制器
默认情况下,Nest 底层使用 Express 库。因此,在 Express 中使用 MVC(Model-View-Controller,模型-视图-控制器)模式的所有技巧同样适用于 Nest。
首先,用 CLI 工具脚手架一个新 Nest 应用:
$ npm i -g @nestjs/cli
$ nest new project要创建 MVC 应用,你还需要一个模板引擎来渲染 HTML 视图:
$ npm install --save hbs本示例使用 hbs(Handlebars)引擎,你也可以用任何符合需求的引擎。安装完成后,用以下代码配置 Express 实例:
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'node:path';
import { AppModule } from './app.module.js';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
);
app.useStaticAssets(join(import.meta.dirname, '..', 'public'));
app.setBaseViewsDir(join(import.meta.dirname, '..', 'views'));
app.setViewEngine('hbs');
await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();import { NestFactory } from '@nestjs/core';
import { join } from 'node:path';
import { AppModule } from './app.module.js';
async function bootstrap() {
const app = await NestFactory.create(
AppModule,
);
app.useStaticAssets(join(import.meta.dirname, '..', 'public'));
app.setBaseViewsDir(join(import.meta.dirname, '..', 'views'));
app.setViewEngine('hbs');
await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();这告诉 Express:public 目录存放静态资源,views 目录存放模板,hbs 模板引擎负责渲染 HTML 输出。
模板渲染
现在创建一个 views 目录,并在其中放置 index.hbs 模板。该模板打印控制器传入的 message:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App</title>
</head>
<body>
{{ message }}
</body>
</html>接着打开 app.controller 文件,把内容替换为以下代码:
import { Get, Controller, Render } from '@nestjs/common';
@Controller()
export class AppController {
@Get()
@Render('index')
root() {
return { message: 'Hello world!' };
}
}这段代码在 @Render() 装饰器中指定要使用的模板,路由处理方法的返回值会传给模板进行渲染。返回值是一个带 message 属性的对象,与模板中的 message 占位符对应。
应用运行期间,用浏览器访问 http://localhost:3000,你应该会看到 Hello world! 消息。
添加布局
hbs 引擎支持布局(layout):即各个视图渲染进去的共享外层模板。要使用布局,请用 setLocal() 方法设置 layout 局部变量(这是 Nest 对 Express app.locals 的封装)。把前面的代码修改如下:
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'node:path';
import { AppModule } from './app.module.js';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
);
app.setLocal('layout', 'layouts/app');
app.useStaticAssets(join(import.meta.dirname, '..', 'public'));
app.setBaseViewsDir(join(import.meta.dirname, '..', 'views'));
app.setViewEngine('hbs');
await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();import { NestFactory } from '@nestjs/core';
import { join } from 'node:path';
import { AppModule } from './app.module.js';
async function bootstrap() {
const app = await NestFactory.create(
AppModule,
);
app.setLocal('layout', 'layouts/app');
app.useStaticAssets(join(import.meta.dirname, '..', 'public'));
app.setBaseViewsDir(join(import.meta.dirname, '..', 'views'));
app.setViewEngine('hbs');
await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();接着在 views 中创建 layouts 文件夹,并添加内容如下的 app.hbs 文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App</title>
</head>
<body>
{{{ body }}}
</body>
</html>然后把 index.hbs 更新为:
{{ message }}最终的文件结构如下:
动态模板渲染
如果应用逻辑必须动态决定渲染哪个模板,请使用 @Res() 装饰器,并在路由处理器中提供视图名,而不是写在 @Render() 装饰器里:
当 Nest 检测到 @Res() 装饰器时,它会注入库特有的 response 对象,你可以用它动态渲染模板。关于 response 对象的更多内容见 Express API 参考。
import { Get, Controller, Res, Render } from '@nestjs/common';
import type { Response } from 'express';
import { AppService } from './app.service.js';
@Controller()
export class AppController {
constructor(private appService: AppService) {}
@Get()
root(@Res() res: Response) {
return res.render(
this.appService.getViewName(),
{ message: 'Hello world!' },
);
}
}示例
可运行的示例见 15-mvc 示例。
Fastify
如 HTTP 适配器一章所述,你可以为 Nest 使用任何兼容的 HTTP 提供者。其中一个库就是 Fastify。要用 Fastify 创建 MVC 应用,请安装以下包:
$ npm i --save @fastify/static @fastify/view handlebars接下来的步骤与 Express 几乎相同,只有少量平台特有的差异。安装完成后,打开 main.ts 文件并更新其内容:
import { NestFactory } from '@nestjs/core';
import { NestFastifyApplication, FastifyAdapter } from '@nestjs/platform-fastify';
import { AppModule } from './app.module.js';
import { join } from 'node:path';
import Handlebars from 'handlebars';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
app.useStaticAssets({
root: join(import.meta.dirname, '..', 'public'),
prefix: '/public/',
});
app.setViewEngine({
engine: {
handlebars: Handlebars,
},
templates: join(import.meta.dirname, '..', 'views'),
});
await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();import { NestFactory } from '@nestjs/core';
import { FastifyAdapter } from '@nestjs/platform-fastify';
import { AppModule } from './app.module.js';
import { join } from 'node:path';
import Handlebars from 'handlebars';
async function bootstrap() {
const app = await NestFactory.create(AppModule, new FastifyAdapter());
app.useStaticAssets({
root: join(import.meta.dirname, '..', 'public'),
prefix: '/public/',
});
app.setViewEngine({
engine: {
handlebars: Handlebars,
},
templates: join(import.meta.dirname, '..', 'views'),
});
await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();Fastify 的 API 有几处差异,但这些方法调用的最终结果相同。一个显著差异是:在 Fastify 下,传给 @Render() 装饰器的模板名必须包含文件扩展名:
import { Get, Controller, Render } from '@nestjs/common';
@Controller()
export class AppController {
@Get()
@Render('index.hbs')
root() {
return { message: 'Hello world!' };
}
}另一种做法是用 @Res() 装饰器直接注入响应,并指定你想渲染的视图,如下所示:
import { Get, Res } from '@nestjs/common';
import type { FastifyReply } from 'fastify';
@Get()
root(@Res() res: FastifyReply) {
return res.view('index.hbs', { message: 'Hello world!' });
}应用运行期间,用浏览器访问 http://localhost:3000,你应该会看到 Hello world! 消息。
示例
可运行的示例见 17-mvc-fastify 示例。