非常教程

Nest参考手册

技术

模型 - 视图 - 控制器

模型 - 视图 - 控制器

默认情况下,Nest使用引擎盖下的快速库。因此,关于MVC(模型 - 视图 - 控制器)模式的每个教程都表达了对Nest的关注。首先,让我们使用CLI工具构建一个简单的Nest应用程序:

$ npm i -g @nestjs/cli
$ nest new project

为了创建MVC应用程序,我们必须安装模板引擎:

$ npm install --save hbs

我们决定使用hbs引擎,但您可以使用符合您要求的任何引擎。安装过程完成后,我们需要使用以下代码配置express实例:

main.ts

JS

import { NestFactory } from '@nestjs/core';
import { join } from 'path';
import { ApplicationModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);

  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('hbs');

  await app.listen(3000);
}
bootstrap();

我们告诉快递,该public目录将用于存储静态资产,views将包含模板,并且hbs应使用模板引擎来呈现HTML输出。

现在,让我们在其中创建一个views目录和index.hbs模板。在模板中,我们将打印message从控制器传递的内容:

index.hbs

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>App</title>
</head>
<body>
  {{ message }}
</body>
</html>

然后,打开app.controller文件并root()使用以下代码替换该方法:

app.controller.ts

JS

import { Get, Controller, Render } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  @Render('index')
  root() {
    return { message: 'Hello world!' };
  }
}

提示事实上,当Nest检测到@Res()装饰器时,它会注入特定于库的response对象。

应用程序运行时,打开浏览器并导航到http://localhost:3000/。你应该看到这条Hello world!消息。

Fastify

如本章所述,我们可以将任何兼容的HTTP提供程序与Nest一起使用。其中一个是一个令人满意的库。为了创建具有fastify的MVC应用程序,我们必须安装以下包:

$ npm i --save fastify point-of-view handlebars

接下来的步骤几乎涵盖了与快速库(具有小差异)的情况相同的内容。安装过程完成后,我们需要打开main.ts文件并更新其内容:

main.ts

JS

import { NestFactory, FastifyAdapter } from '@nestjs/core';
import { ApplicationModule } from './app.module';
import { join } from 'path';

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule, new FastifyAdapter());
  app.useStaticAssets({
    root: join(__dirname, '..', public'),
    prefix: '/public/',
  });
  app.setViewEngine({
    engine: {
      handlebars: require('handlebars'),
    },
    templates: join(__dirname, '..', 'views'),
  });
  await app.listen(3000);
}
bootstrap();

API略有不同,但这些方法调用背后的想法保持不变。此外,我们必须确保传递给@Render()装饰器的模板名称包含文件扩展名。

app.controller.ts

JS

import { Get, Controller, Render } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  @Render('index.hbs')
  root() {
    return { message: 'Hello world!' };
  }
}

应用程序运行时,打开浏览器并导航到http://localhost:3000/。你应该看到这条Hello world!消息。

Nest

Nest 是一个用于构建高效,可扩展的 Node.js 服务器端应用程序的框架

Nest目录

1.介绍
2.常见问题
3.CLI
4.方法
5.执行上下文
6.微服务
7.WEBSOCKETS
8.GRAPHQL
9.技术
10.基本内容
11.迁移指南