This article will introduce you to the Nest.js framework in node, and talk about why you choose Nest, how to create and run projects, and receive requests in different ways. I hope it will be helpful to everyone!
Recently I am considering making a todolist platform with my friends for my own use. I learned express
a long time ago and want to keep pace with the times. Let’s take a look Let’s take a look at some of the most popular frameworks recently. After several comparisons, I chose nest
and recorded it after initial use for future reference.
Post Chinese documents for further studyNest
Introduction to Nest.js framework
- Nest is a framework for building efficient, reliable Extended Node.js Framework for server-side applications. It uses Progressive JavaScript, has built-in and full support for TypeScript (but still allows developers to write code in pure JavaScript) and combines OOP (Object Oriented Programming), FP (Functional Programming) and FRP (Functional Programming) elements of reactive programming.
- The underlying HTTP platform of the Nest framework is implemented based on Express by default, so there is no need to worry about the lack of third-party libraries. Nest aims to be a platform-agnostic framework. The platform enables the creation of reusable logical components that developers can leverage across many different types of applications. Nest currently has two HTTP platforms that support out-of-the-box: express and fastify, which can be introduced directly in the project.
Why choose Nest
- There are many node frameworks on the market for you to choose from.
- Express.js is the birth of Node.JS. It is a fast and minimalist JS server-side development framework based on Node.js and Chrome V8 engine.
- Koa.js is a micro Web framework. It is very simple to write a hello world, but web applications are inseparable from sessions, view templates, routing, file uploads, and log management. These are not provided by Koa, so you need to go to the official Middleware to find them. However, 100 people may find 100 combinations.
- Egg.js is based on Koa.js, which solves the above problems, integrates the best practices of the community into Koa.js, and is also named Egg.js, and starts multiple processes to make development easier. Update and other issues were solved together. This is very developer friendly, it works right out of the box, and it has the best (better) configuration right out of the box. During the development of Egg.js, ECMAScript introduced async await. Compared with the yield syntax, async is more straightforward to write. Later, Koa.js also followed up.
- Midway is a Node.js framework developed by the Alibaba team based on the progressive concept, combining OOP and functional programming paradigms. With egg as the underlying framework, and many new features such as good TypeScript definition support, Midway is launched. Interested friends can go to the official documentation to learn
- Nest.js based on Express.js The full-featured framework Nest.js is packaged on Express.js and makes full use of the characteristics of TypeScript; the advantage of Nest.js is that the community is active and the growth is gratifying. As of now, it has ## in GitHub #43.7k Star
is a popular enterprise-level framework recently.
Based on the comprehensive consideration of supporting underlying support ts and enterprise level and community activity, here I choose to use nest for learning. Students can choose according to their needs. -
Create project
Create project
$ npm i -g @nestjs/cli
$ nest new project-name
After creating the project, take a look at the project directory. The following is a brief description of the core file:
app.controller.ts | Basic controller example with a single route |
app.controller.spec.ts | Unit test sample for basic controller |
app.module.ts | The root module of the application. |
app.service.ts | Basic service with a single method |
main.ts | Application entry file. Used to create Nest application instances. |
/* main.ts */
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule); // 使用核心类 NestFactory 返回一个 接口对象
await app.listen(3000); // 这里是默认设置的端口号
}
bootstrap();
运行项目
路由
在开始写代码之前我们先简单看一下nest中的基础路由配置是怎样的,就目前而言我的理解为nest的路由是由
全局路由 路由前缀(局部路由) 方法装饰器 组成路由映射提供给前端使用。
/* main.ts */
main文件中我们可以在项目监听前配置一个全局的api前缀
async function bootstrap() {
const app = await NestFactory.create(AppModule);
//设置全局前缀
app.setGlobalPrefix('api');
await app.listen(3000);
}
/* app.controller.ts */
@Controller('user') // 控制器设置路由前缀 我理解为局部路由
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('find') // 方法装饰器设置路由路径 这里我理解为设置api子路由
getHello(): string {
return this.appService.getHello();
}
}
以上方法在api中映射成完整的路由为GET api/user/find
。
其中 @Get()HTTP请求装饰器告诉Nest为HTTP请求的特定端点创建处理程序。
- 可以看到上面的
get
接收请求及路由以可以使用,下面我们看一下 nest
中如何接收 post
等其他请求方式
不同方式接收请求
-
这里用到的 Nest 提供的请求装饰器知识点Request
对象代表 HTTP
请求,并具有查询字符串,请求参数参数,HTTP 标头(HTTP header) 和 正文(HTTP body)的属性(在这里阅读更多)。在多数情况下,不必手动获取它们。 我们可以使用专用的装饰器,比如开箱即用的 @Body()
或 @Query()
。 下面是 Nest 提供的装饰器及其代表的底层平台特定对象的对照列表。
下面我们看一下 nest 中如何接收 get post put delete
发起的请求,用几个可用的装饰器来创建基本控制器。 该控制器暴露了几个访问和操作内部数据的方法。
Get
-
我们先创建一个 user 服务/控制器/moudle
/ * user.service.ts */ 先创建一个 user service服务文件
import { Injectable } from '@nestjs/common';
@Injectable() //
// 这里
export class UserService {
findUser(sid: string): string {
console.log(sid);
if (sid === '123456') {
return 'kid is here';
}
return 'No one here';
}
}
-
该服务将负责数据存储和检索,其由 UserController
使用,我们用 @Injectable()
来装饰这个类
/ * user.controller.ts */ 创建一个 user 控制器文件
import { Controller, Get, Query } from '@nestjs/common';
import { UserService } from './user.service';
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get('findOne') //这里暴露出的路由为 user/find
findUser(@Query() query: any) {
return this.userService.findUser(query.sid);
}
控制器的目的是接收应用的特定请求。路由机制控制哪个控制器接收哪些请求。通常,每个控制器有多个路由,不同的路由可以执行不同的操作。
-
为了创建一个基本的控制器,我们使用类和装饰器
。装饰器将类与所需的元数据相关联,并使 Nest 能够创建路由映射(将请求绑定到相应的控制器)。
/ * user.module.ts */ 创建一个 user mod
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';
@Module({
controllers: [UserController],
providers: [UserService],
})
export class UserModule {}
/* app.module.ts */ 最后在app.module中引入我们自己写的module
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
@Module({
imports: [UserModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
控制器已经准备就绪,可以使用,但是 Nest 依然不知道 UserController
是否存在,所以它不会创建这个类的一个实例。
-
控制器总是属于模块,这就是为什么我们在 @Module()
装饰器中包含 controllers
数组的原因。 由于除了根模块 AppModule
之外,我们还没有定义其他模块,所以我们将使用它来介绍 UserController
使用 postman 看下效果
- 可以看到发送get请求 请求成攻。
- 接下来我们依次使用
post put delete
发送请求,看nest是如何接受并处理的
Post
-
user.service 文件
/ * user.service.ts */ 先创建一个 user service服务文件
import { Injectable } from '@nestjs/common';
@Injectable() //
// 这里
setUser(sid: string, body: any): any {
if (sid === '123456') {
return {
msg: '设置成功',
body,
};
}
}
-
user.controller 文件
/ * user.controller.ts */ 创建一个 user 控制器文件
import { Controller, Get, Query } from '@nestjs/common';
import { UserService } from './user.service';
@Controller('user')
export class UserService {
@Post('set')
setUser(@Body() body: any, @Query() query: any) {
return this.userService.setUser(query.sid, body);
}
}
使用 postman 看下效果
Put
-
user.service 文件
/ * user.service.ts */ 先创建一个 user service服务文件
import { Injectable } from '@nestjs/common';
@Injectable() //
// 这里
updateUser(sid: string, body: any): any {
if (sid === '123456') {
return {
msg: '设置成功',
body,
};
}
}
user.controller 文件
-
这里用到了 Param 装饰器 @Param()
用于修饰一个方法的参数(上面示例中的 params
),并在该方法内将路由参数作为被修饰的方法参数的属性。如上面的代码所示,我们可以通过引用 params.id
来访问(路由路径中的) id
参数。 您还可以将特定的参数标记传递给装饰器,然后在方法主体中按参数名称直接引用路由参数。
/ * user.controller.ts */ 创建一个 user 控制器文件
import { Body, Controller, Get, Param, Post, Put, Query } from '@nestjs/common';
import { UserService } from './user.service';
@Controller('user')
export class UserService {
@Put(':sid')
updateUser(@Param('sid') sid: string, @Body() body: any) {
return this.userService.updateUser(sid, body);
}
}
使用 postman 看下效果
Delete
-
user.service 文件
/ * user.service.ts */ 先创建一个 user service服务文件
import { Injectable } from '@nestjs/common';
@Injectable() //
// 这里
deleteUser(sid: string): any {
if (sid === '123456') {
return {
msg: '删除成功',
};
}
}
-
user.controller 文件
/ * user.controller.ts */ 创建一个 user 控制器文件
import { Body, Controller, Get, Param, Post, Put, Query } from '@nestjs/common';
import { UserService } from './user.service';
@Controller('user')
export class UserService {
@Delete(':sid')
deleteUser(@Param('sid') sid: string) {
return this.userService.deleteUser(sid);
}
}
使用 postman 看下效果
总结
- 至此我们用 Nest 的装饰器模拟了基础的接口请求增删改查,认识到 Nest 中的三种基本应用程序构建块
Module Controller Service
- 服务和控制的划分明确,带来更好的代码体验。
TypeScrip
的个人使用还有待提高,以后还要继续学习hhh
更多node相关知识,请访问:nodejs 教程!
The above is the detailed content of An in-depth analysis of the Nest.js framework in node. For more information, please follow other related articles on the PHP Chinese website!